Skip to content

Instantly share code, notes, and snippets.

@railsstudent
Created November 12, 2017 10:00
Show Gist options
  • Save railsstudent/b278564e270dab0801a58ed80ba9baef to your computer and use it in GitHub Desktop.
Save railsstudent/b278564e270dab0801a58ed80ba9baef to your computer and use it in GitHub Desktop.
// Async function returns promise
async function asyncFunc() {
return "123";
}
async function resolveAfter1Second(n) {
return new Promise(resolve => {
setTimeout(() => {
resolve(n);
}, 1000);
});
}
const sumFunc = async() => {
const n1 = await resolveAfter1Second(10);
const n2 = await resolveAfter1Second(20);
const n3 = await resolveAfter1Second(30);
return n1 + n2 + n3;
}
// use sequential await
async function resolveAfterNSecond(num, sec) {
return new Promise(resolve => {
setTimeout(() => {
resolve(num);
}, sec * 1000);
});
}
// Resolve promise in sequential order
const multFunc = async() => {
const n1 = await resolveAfterNSecond(2, 1);
const n2 = await resolveAfterNSecond(3, 2);
const n3 = await resolveAfterNSecond(4, 3);
return n1 * n2 * n3;
}
// Use promise.all to resolve promises in parallel
const multFuncParallel = async() => {
const [n1, n2, n3] = await Promise.all([resolveAfterNSecond(2, 1), resolveAfterNSecond(3, 2), resolveAfterNSecond(4, 3)]);
return n1 * n2 * n3;
}
module.exports = {
asyncFunc,
sumFunc,
multFunc,
multFuncParallel
};
// Call async functions in separate file
const a = require('./asyncFunc');
a.asyncFunc()
.then(console.log);
// expect 60
a.sumFunc()
.then(console.log)
.catch(console.error);
a.multFunc()
.then(console.log)
.catch(console.error);
a.multFuncParallel()
.then(console.log)
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment