Skip to content

Instantly share code, notes, and snippets.

@pinei
Created January 19, 2023 03:50
Show Gist options
  • Select an option

  • Save pinei/229f163078d97b2e4dfa34ddf5462aee to your computer and use it in GitHub Desktop.

Select an option

Save pinei/229f163078d97b2e4dfa34ddf5462aee to your computer and use it in GitHub Desktop.
Promise with Javascript
const work = async (id) => new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`${(new Date()).toISOString()}: ${id}`)
resolve()
}, 1000)
});
async function test1() {
// parallel
work('1.1')
work('1.2')
work('1.3')
work('1.4')
}
async function test2() {
// sequential
await work('2.1')
await work('2.2')
await work('2.3')
await work('2.4')
}
async function test3() {
// sequential
for (let i of ['3.1', '3.2', '3.3', '3.4']) {
await work(i)
}
}
async function test4() {
// parallel
['4.1', '4.2', '4.3', '4.4'].forEach(async (i) => await work(i))
}
async function test5() {
// parallel
let promises = ['5.1', '5.2', '5.3', '5.4'].map((i) => work(i))
await Promise.all(promises)
}
async function test5() {
// parallel
let promises = ['5.1', '5.2', '5.3', '5.4'].map((i) => work(i))
await Promise. all(promises)
}
(async () => {
await test1()
await test2()
await test3()
await test4()
await test5()
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment