So conceptually, async/await is just replacing the `await someMethod()` statement with the first argument to `resolve` or calling `catch()` with the first argument of `reject`?
// this
var x = await promise;
callSomething(x);
// translates as
promise.then(x => callSomething(x));
Under the hood, the entire "async" function is turned into a state machine instead of creating a lot of callbacks. It's more efficient it can do some optimizations that would be boring to do manually.For example, if the translation were simply "turn into callbacks", this:
var p = getJson();
var x = await p;
var y = await p;
var z = await p;
would translate to something like : var p = getJson();
p.then(o => { var x = o; });
p.then(o => { var y = o; });
p.then(o => { var z = o; });
but instead, the code runs more like this: getJson().then(o => {
var x = o;
var y = o;
var z = o;
});
I say runs like because the compiled code is more complex than that, it will still call functions, etc. It will also handle exceptions, which would add a lot of boilerplate to this code. But have in mind that because this is generated by the compiler, this code will in most cases be more efficient than anything you try to write by hand.So conceptually, it's what I described; but in practice, it's optimized?
while (somecondition) {
try {
await sleep(1000);
somecondition = await someAsyncAction();
} catch(err) {
}
}
Doing retries, or loops against promise actions are really cumbersome with promises directly, but with async/await becomes much more clear in terms of action and intent. function iff(condition, method) {
return Promise.try(condition).then(result => {
if (result) {
return method();
}
});
}
function whilst(condition, method) {
return iff(condition, () => {
return Promise.try(method)
.then(whilst.bind(null, condition, method));
});
}
whilst(someAsyncAction, Promise.sleep.bind(null, 1000))
.catch(err => {
// ...
})
Naturally you wouldn't want to re-implement all of this control flow every time you need it. But the end result is not too much boilerplate.