Re:JavaScript async/await implemented in V8
by xg15 on Tuesday May 17, 2016 @07:24AM
(#11712654)
There is also the the point of flexibility. Async/await works on promises, however promises themself are just perfectly un-magical JS objects that accept a callback. This results in two effects:
1) Yielding is decoupled from the asynchronous action itself, giving the caller fine-grained control when to yield. For example, with async/await, management of parallel operations is straight-forward:
var promise = fetch('https://foo.com/');
// ... do something useful while the fetch runs ...
var result = yield promise;
Same goes for concurrent fetches:
var promise1 = fetch('https://foo.com/');
var promise2 = fetch('https://bar.com/');
[result1, result2] = yield Promise.all(promise1, promise2 );
2) Promises + async/await allow you to switch back-and-forth very easily between callback-style and coroutine-style APIs, which makes integrating old APIs very easy:
async function f() {
var p = fetch('https://foo.com/');
p = p.then(function(inbetweenResult) {return new Promise(function(resolve) {
oldapi.onresult = resolve;
oldapi.process(inbetweenResult);
})});
return await p;
}
f().then(...)
1) Yielding is decoupled from the asynchronous action itself, giving the caller fine-grained control when to yield. For example, with async/await, management of parallel operations is straight-forward:
Same goes for concurrent fetches: 2) Promises + async/await allow you to switch back-and-forth very easily between callback-style and coroutine-style APIs, which makes integrating old APIs very easy: ... and so on.