generated from pesto-students/PestoPlus
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
async-await part of question is solved.
- Loading branch information
1 parent
20590e2
commit 6e48a45
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |