As far as I know, async/awaitthis is just syntactic sugar over promise.then. Consider this piece of code:
function sleep(n){
return new Promise(res => setTimeout(res, n));
}
function* range(n){
var i = 0;
while(i < n) yield i++;
}
async function doStuff(){
for(let n of range(10)){
console.log(n);
await sleep(1000);
}
}
async/awaitmakes the code very linear, efficient and clear. It should be borne in mind that rangethere should not be an actual end for this.
Now the problem is how this can be rewritten using the era of ES7 to ES7 promise.then. It is possible to implement the same cycle:
function doStuff(){
return Array.from(range(10)).reduce((acc, ele) => {
return acc
.then(() => console.log(ele))
.then(() => sleep(1000))
}, Promise.resolve());
}
Ignoring the fact that the code is not very elegant, use Array.from(range(10))
- creates an additional array that is not needed, and
- It is expected to
range(10)end in the future.
Not like a good conversion.
, yield await, ES5. :
?