Created
December 7, 2017 10:27
-
-
Save tuchk4/036803bb38586a0c4e605dce01a5658b to your computer and use it in GitHub Desktop.
#1 ― async / await (KharkivJS)
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 squareAfter2Seconds(x) { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
resolve(x * x); | |
}, 2000); | |
}); | |
} | |
async function calc() { | |
const a = await squareAfter2Seconds(10); | |
const b = await squareAfter2Seconds(20); | |
const c = await squareAfter2Seconds(30); | |
console.log(a + b + c); | |
} | |
calc(); |
kazminigor1988
commented
Dec 7, 2017
•
Работать будет, но не самое красивое решение
function squareAfter2Seconds(x) {
return new Promise( res => {
setTimeout(() => {
res(x * x);
}, 2000);
});
}
async function calc() {
const a = squareAfter2Seconds(10);
const b = squareAfter2Seconds(20);
const c = squareAfter2Seconds(30);
console.log(await a + await b + await c);
}
calc();
да, самый ок вариант.
убрал ссылку на гист из топика, а то не интересно будет
Поскольку не успел - хоть сахару добавлю
async function calc() {
const [ a, b, c ] = [ 10, 20, 30 ].map( n => squareAfter2Seconds( n ) );
console.log(await a + await b + await c);
}
Если совсем упороться, можно еще и без переменных )
(btw но так делать не нужно никогда)
async function calc() {
console.log(
await [ 10, 20, 30 ]
.map(async x => await squareAfter2Seconds(x))
.reduce(async (a, b) => await a + await b)
)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment