I was playing around with the current experimental implementation of async
/await
in Babel and thought it might be cool to be able to await
on arguments. The most basic example:
async function double(await num) {
return num * 2;
}
This is the same as the following ES6:
function double(num) {
return num.then(x => x * 2);
}
Or the following ES5:
function double(num) {
return num.then(function (x) {
return x * 2;
});
}
As another example, consider await
ing on multiple arguments:
async function multiply(await first, await second) {
return first * second;
}
~~As far as I'm aware, this is the best analog in the current proposal:~~
Better analog (as pointed out in the comments):
async function multiply(first, second) {
[first, second] = [await first, await second];
return first * second;
}
And as far as I'm aware, this is the best analog in ES6:
function multiply(first, second) {
return Promise.all([first, second]).then(([a, b]) => a * b);
}
Extending this even further, we can use the new ES6 arguments functionality with await
:
async function multiply(await {num: first}, await {num: second}) {
return first * second;
}
Which is the same as:
function multiply(first, second) {
return Promise.all([first, second]).then(([{num: first}, {num: second}]) => first * second);
}
Additional example for await
ing on a property of an argument:
async function double({await num}) {
return num * 2;
}
Which is the same as:
function double(obj) {
return obj.then(({num}) => num * 2);
}