ES6 must know (8) - async function

async function

1. The ES2017 standard introduces the async function, which is an improvement to the Generator function. Let's first look at an example of reading a file:

Generator is written like this:

var fs = require('fs');

var readFile = function (fileName) { return new Promise(function (resolve, reject) { fs.readFile(fileName, function(error, data) { if (error) return reject(error); resolve(data); }); }); }; var gen = function* () { var f1 = yield readFile('/etc/fstab'); var f2 = yield readFile('/etc/shells'); console.log(f1.toString()); console.log(f2.toString()); }; 

Async is written as follows:

var asyncReadFile = async function () { var f1 = await readFile('/etc/fstab'); var f2 = await readFile('/etc/shells'); console.log(f1.toString()); console.log(f2.toString()); }; 

It is found that the async function is to replace the asterisk (*) of the Generator function with async, and replace the yield with await. At the same time, the co module is not required, which is more semantic;

2. The async function returns a Promise object, and the value returned by the internal return statement will become the parameter of the then method callback function;

async function f() { return 'hello world'; } f().then(res => console.log(res)) // "hello world" 

3. The Promise object returned by the async function must wait until all the promise objects behind the await command are executed before the state changes, unless a return statement is encountered or an error is thrown. That is to say, the callback function specified by the then method will be executed only after the asynchronous operation inside the async function is executed;

4. If an error is thrown inside the async function, the returned Promise object will change to the reject state, and the thrown error object will be received by the catch method callback function;

async function f() { throw new Error('出错了'); } f().then( res => console.log(res), err => console.log(err) ) // Error: 出错了 

5. The await command is followed by a Promise object. If not, it will be converted to a Promise object that resolves immediately

async function f() { return await 'Hello World'; } f().then(res => console.log(res)) // 'Hello World' 

In the above code, the parameter of the await command is 'Hello World', which is converted into a Promise object and resolved immediately

6. If the Promise object behind the await command becomes the reject state, the parameters of the reject will be received by the callback function of the catch method

async function f() { await Promise.reject('出错了'); } f().then(res => console.log(res)) .catch(err => console.log(err)) // 出错了 

7. In the async function, as long as the Promise behind an await statement becomes reject, the entire async function will be interrupted execution;

async function f() { await Promise.reject('出错了'); await Promise.resolve('hello world'); // 不会执行 } f(); // 出错了 

8. If we want to not interrupt subsequent async operations even if the previous one fails. Then we can put the first await in the try...catch structure, so that the second await will be executed regardless of whether the asynchronous operation is successful or not;

async function f() { try { await Promise.reject('出错了'); } catch(e) { } return await Promise.resolve('hello world'); } f().then(res => console.log(res)) // hello world 

Or the Promise object behind await is followed by a catch method to deal with possible errors:

async function f() { await Promise.reject('出错了') .catch(err => console.log(err)); return await Promise.resolve('hello world'); } f() .then(res => console.log(res)) // 出错了 // hello world 

9. If there is an error in the asynchronous operation behind await, then the Promise object equivalent to that returned by the async function is rejected:

async function f() { await new Promise(function (resolve, reject) { throw new Error('出错了'); }); } f().then(res => console.log(res)) .catch(err => console.log(err)) // Error:出错了 

10. In order to prevent errors, the practice is also to put it in the try...catch code block, and if there are multiple await commands, they can be placed in the try...catch structure.

async function f() { try { await new Promise(function (resolve, reject) { throw new Error('出错了'); }); } catch(e) { } return await('hello world'); } f().then( res => console.log(res) ) // 'hello world' 

11. Pay attention to the following points when using await:

  • The Promise object after the await command may be rejected, so it is best to put the await command in the try...catch code block

     async function myFunction() { try { await operations(); } catch (err) { console.log(err); } } // 另一种写法 async function myFunction() { await operations() .catch(function (err) { console.log(err); }); } 
  • Asynchronous operations behind multiple await commands, if there is no secondary relationship (that is, independent of each other), it is best to let them trigger at the same time to shorten the execution time of the program

     // 写法一
     let [foo, bar] = await Promise.all([getFoo(), getBar()]);
    
     // 写法二 let fooPromise = getFoo(); let barPromise = getBar(); let foo = await fooPromise; let bar = await barPromise; 
  • The await command can only be used in async functions. If it is used in ordinary functions, an error will be reported.

     async function func(db) { let docs = [{}, {}, {}]; // 报错 docs.forEach(function (doc) { await db.post(doc); }); }




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326045003&siteId=291194637