Last active
October 14, 2020 01:13
-
-
Save shuuuuun/b84bcd7bc5f5127551f8c8ed844b4aae to your computer and use it in GitHub Desktop.
promise-memo.js
This file contains hidden or 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
// 並列実行 | |
;(async () => { | |
const sleepTimes = [1000, 2000, 3000] | |
// この時点で実行開始される | |
const promises = sleepTimes.map((num) => new Promise((resolve, _reject) => { | |
setTimeout(() => { | |
const now = new Date() | |
console.log(`${num} msec later. ${now}`) | |
resolve(now) | |
}, num) | |
})) | |
const values = await Promise.all(promises) | |
console.log(`end. ${values}`) | |
})() | |
// 直列実行 | |
;(async () => { | |
const sleepTimes = [1000, 2000, 3000] | |
// まだ実行してほしくないので、promiseオブジェクトではなくpromiseを返す関数を返す | |
const promises = sleepTimes.map((num) => () => new Promise((resolve, _reject) => { | |
setTimeout(() => { | |
console.log(`${num} msec sleeping...`) | |
const now = new Date() | |
console.log(`${num} msec later. ${now}`) | |
resolve(now) | |
}, num) | |
})) | |
const values = await promises.reduce((acc, val) => acc.then(val), Promise.resolve()).catch(console.error) | |
console.log(`end. ${values}`) | |
})() | |
// 直列実行 async版 | |
;(async () => { | |
const sleepTimes = [1000, 2000, 3000] | |
const sleep = (msec) => { | |
return new Promise(resolve => { | |
setTimeout(resolve, msec) | |
}) | |
} | |
// まだ実行してほしくないので、promiseオブジェクトではなくpromiseを返す関数を返す | |
const promises = sleepTimes.map((num) => (async () => { | |
console.log(`${num} msec sleeping...`) | |
await sleep(num) | |
const now = new Date() | |
console.log(`${num} msec later. ${now}`) | |
return now | |
})) | |
const values = await promises.reduce((acc, val) => acc.then(val), Promise.resolve()).catch(console.error) | |
console.log(`end. ${values}`) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment