Skip to content

Commit

Permalink
async-await part of question is solved.
Browse files Browse the repository at this point in the history
  • Loading branch information
mrkarthik3 committed Apr 30, 2022
1 parent 20590e2 commit 6e48a45
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions Week-5/Async-Await-Generators/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// These are callbacks

function doTask1(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`task1 done after ${ms / 1000} seconds`);
}, ms);
});
}
function doTask2(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`task2 done after ${ms / 1000} seconds`);
}, ms);
});
}
function doTask3(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(`rejected!! after ${ms / 1000} seconds `);
}, ms);
});
}

async function asyncDemo() {
// whatever value a promise resolves with is taken by variables
const result1 = await doTask1(2000);
console.log(result1);
const result2 = await doTask2(5000);
console.log(result2);
// if promise rejects, I am using 'try-catch' block

try {
const result3 = await doTask3(2000);
console.log(result3);
} catch (rejectMessage) {
console.log(rejectMessage);
}
// Here I used .catch()
const result4 = await doTask3(4000).catch((rejectMessage) =>
console.log(rejectMessage)
);
}

// async-await functionality achieved.
asyncDemo();

// Now I will try to achieve the same functionality using Generators

0 comments on commit 6e48a45

Please sign in to comment.