Created
September 18, 2020 08:20
-
-
Save ever-dev/9fd8d4385aa81bbcf7e04ad99844d56e to your computer and use it in GitHub Desktop.
Promise in Arrays
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
function promiseFunction(v) { | |
return new Promise((resolve) => { | |
setTimeout(() => resolve(v), 1000); | |
}); | |
} | |
// f1() will print `all done` first and then print 1,2,3,4 at once after a second. | |
function f1() { | |
[1, 2, 3, 4]. forEach(async(i) => { | |
const v = await promiseFunction(i); | |
console.log('-v-', v); | |
}); | |
console.log('all done'); | |
} | |
// f2() will print 1,2,3,4 at once after a second then print `all done`. | |
async function f2() { | |
await Promise.all([1, 2, 3, 4].map(async(i) => { | |
const v = await promiseFunction(i); | |
console.log('-v-', v); | |
})); | |
console.log('all done'); | |
} | |
// f3() will print 1,2,3,4 in every second, and then print `all done`. | |
async function f3() { | |
await [1, 2, 3, 4].reduce((p, i) => { | |
return p.then(async () => { | |
const v = await promiseFunction(i); | |
console.log('-v-', v); | |
}); | |
}, Promise.resolve()); | |
console.log('all done'); | |
} | |
// What async function returns is actually a promise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment