returns a promise. When the async func,on returns a value, the promise will be resolved with the returned value. When the async func,on throws an excep,on or some value, the promise will be rejected with the thrown value. Async func)on can contain await expression, that pauses the execu)on of the async func)on and waits for the passed promise's resolu)on, and resumes the async func)on's execu)on and returns the resolved value.
new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function add1(x) { let a = resolveAfter2Seconds(20); let b = resolveAfter2Seconds(30); return x + await a + await b; } add1(10).then(v => { console.log(v); // prints 60 after 2 seconds. });
new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function add2(x) { let a = await resolveAfter2Seconds(20); let b = await resolveAfter2Seconds(30); return x + a + b; } add2(10).then(v => { console.log(v); // prints 60 after 4 seconds. });
Example 1: async function something(request, response) { try { let user = await User.get(request.user); let notebook = await Notebook.get(user.notebook); let result = await doSomethingAsync(user, notebook); response.send(result); } catch(err) { response.send(err); } }
the return value of the func%on in a promise. Under the hood it is more or less using generators, but all of that is hidden away behind this simple syntax. await "Hello!" What if it's a non-promise? Will this work?
and later re-entered. Their context (le-able bindings) will be saved across re-entrances. Syntax function* name([param[, param[, ... param]]]) { statements }
its body immediately; an iterator object for the func/on is returned instead. When the iterator's next() method is called, the generator func/on's body is executed un/l the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator func/on.
"userId": 1, "id": 1, "title": "sunt aut facere repellat provident", "body": "suscipit recusandae consequuntur expedita" } const co = require('co'); const fetch = require('node-fetch'); co(function* (){ let uri = 'https://jsonplaceholder.typicode.com/posts/1'; let response = yield fetch(uri); let post = yield response.json(); console.log('Title: ', post.title); // sunt aut facere repellat provident });
in JavaScript • Iterators and Generators • Async Func@on • From Callbacks to Promises to Generators to Async/await • The Hidden Power of ES6 Generators • Generators in JavaScript [Video] • Async Programming in ES7 [Video]