Async functions, also referred to by the operative keyword pair “async/await,” are the application of the ES6 Promise paradigm to ECMAScript functions. It allows for JavaScript code which is written in a synchronous fashion, but actually is able to behave asynchronously.
What problem exists now? With promise, we write this kind of code:
function handler(x) { console.log(x); }
let p = new Promise((resolve, reject) => setTimeout(resolve, 1000, 3));
p.then(handler); // 3
Any subsequent code that wishes to access the value produced by the promise needs to be fed that value through a handler, which means being shoved into a handler function.
ES7’s async/await is intended to directly address the issue of organizing code which makes use of asynchronous constructs.
How to use? An async function can be declared by prepending the async
keyword. This keyword can be used on function declarations, function expressions, arrow functions, and methods.
Using the async keyword will create a function that exhibits some asynchronous characteristics but overall is still synchronously evaluated. In all other respects such as argumetns and closures, it still exhibits all the normal behavior of a JavaScript function.
In an async function, whatever value is returned with the return keyword (or undefined
if there is no return) will be effectively converted into a promise object with Promise.resolve()
. An async function will always return a promise object. A thenable object will be “unwrapped” via the first argument provided to the then()
callback. A non-thenable object will be passed through as if it were an already resolved promise.
iteration protocal 包括 iterator与iterable
iterable是实现了@@Iterator 的对象。用于for…in循环等。@@itertator 要求为iterator,一般为generator。
iterator是一个具有next()方法的对象。该方法返回一个对象,这个对象至少包含两个属性:done和value。
generator即是iterator,又是itetable。
async就是generator+自动执行器,await就是yield。
下图为用 generator + spawn(自动执行器)模拟的#
Reference: