Home  >  Article  >  Web Front-end  >  How to optimize node Async/Await asynchronous programming

How to optimize node Async/Await asynchronous programming

php中世界最好的语言
php中世界最好的语言Original
2018-05-30 14:52:041117browse

This time I will bring you how to optimize node Async/Await asynchronous Programming, what are the precautions for optimizing node Async/Await asynchronous programming, the following is a practical case, let's come together take a look.

1. The ultimate solution to asynchronous programming

I wrote an article about javascript asynchronous operations a few days ago. Detailed explanation of Javascript Promise. Recently, when I was learning Puppeteer, I discovered another asynchronous programming solution: Async/Await. program to try to solve this problem. From the earliest

callback function

, to the Promise object, and then to the Generator function, there are improvements every time, but it feels incomplete. They all have additional complexities and require an understanding of the underlying underlying operating mechanisms of the abstraction. After the Async function came out, some people thought it was the ultimate solution to asynchronous programming. Because with Async/Await, you don't have to worry about whether it is asynchronous programming.

2. Basic UsageThe async function returns a Promise object, and you can use the then method to add a callback function. When the function is executed, once it encounters await, it will return first, wait until the triggered asynchronous operation is completed, and then execute the subsequent statements in the function body.

The following is a chestnut:

var sleep = function (time) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve();
    }, time);
  })
};
var start = async function () {
  // 在这里使用起来就像同步代码那样直观
  console.log('start');
  await sleep(3000);
  console.log('end');
};
start();

Execute the above code, you will find that the console first outputs start, and after waiting for 3 seconds, it outputs end.

3. Notes1. The await command can only be used in async functions. If used in ordinary functions, an error will be reported. .

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

2. Await means waiting for the promise to return the result before continuing execution.

var sleep = function (time) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      // 返回 ‘ok'
      resolve('ok');
    }, time);
  })
};
var start = async function () {
  let result = await sleep(3000);
  console.log(result); // 收到 ‘ok'
};

3. await should be followed by a promise object.

If the code is executed synchronously, there is no need to use await modification.

4. Await can only be used in native syntax. For example, using await in the forEeach structure will not work properly. You must use the native syntax of the for loop.

async function dbFuc(db) {
 let docs = [{}, {}, {}];
 // 可能得到错误结果
 docs.forEach(async function (doc) {
  await db.post(doc);
 });
}

If you really want multiple requests to be executed concurrently, you can use the Promise.all method.

async function dbFuc(db) {
 let docs = [{}, {}, {}];
 let promises = docs.map((doc) => db.post(doc));
 let results = await Promise.all(promises);
 console.log(results);
}

4. Error capturingSince there is no need to write .then(..), then there is no need to write .catch(..) either , you can directly use the standard try catch syntax to catch errors.

var sleep = function (time) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      // 模拟出错了,返回 ‘error'
      reject('error');
    }, time);
  })
};
var start = async function () {
  try {
    console.log('start');
    await sleep(3000); // 这里得到了一个返回错误
    
    // 所以以下代码不会被执行了
    console.log('end');
  } catch (err) {
    console.log(err); // 这里捕捉到错误 `error`
  }
};

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How React implements login verification control in react-router routing


The routing guard in Angular routing how to use

The above is the detailed content of How to optimize node Async/Await asynchronous programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn