A few days ago in the interview, the interviewer asked me a question THAT I had not considered before: Q: For example, there is a scenario where async/await is used to process asynchronous logic, but async/await is used to wait for one execution before the next one is executed. How can we improve the efficiency of simultaneous execution of multiple asynchronous logic?

To be honest, I was a little confused when I heard that I was waiting for the asynchronous processing to be finished with await and then obtaining the result for operation. Simply speaking, I only triggered the asynchronous operation once and did not consider the concurrent scenario. The interviewer later guided me, saying how to realize multiple asynchronous request concurrent operation in promise. I said I should use promise.all, but the interviewer had to say that async/await is a new solution than Promise, so I would not go backward. In fact, I should have been prompted almost, and I also wanted to say the principle of Promise. The interviewer didn’t ask too much.

After all, there are a lot of scenarios for this question, so I think it is necessary to know about it, but most of the online searches are about how to use async/await, so I thought of Ruan Yifeng’s ES6 introduction, and sure enough, I found the answer. Click to view the original article

let foo = await getFoo();
let bar = await getBar();
Copy the code

Internal execution of async functions is a secondary relation, that is, execution one by one. But if there is no such relation between multiple await functions, concurrent execution will undoubtedly increase the efficiency greatly, so we can change the writing method:

/ / write one
let [foo, bar] = await Promise.all([getFoo(), getBar()]);

/ / write two
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;

/ / writing three

[getFoo, getBar].forEach(async item=> await item())
Copy the code

GetFoo and getBar are two unrelated asynchronous functions,

The first method is implemented with the promise. all method, passing them to promise. all to execute concurrently and waiting for all thenable functions (await must be followed by such a function) to complete.

In addition

Promise. The behavior of all is: A,B, and C all resolve, then resolve, as long as there is A reject, then reject, which is obviously not what we need. [A(), B(), C()], reject (), reject (), Promise ()), reject (), reject (), Promise ()), reject (), reject ()), Promise ()). All of the promises in this new promise array are resolveCopy the code

So we could write it this way

async function dbFuc(db) {
  let docs = [{}, {}, {}];
  let promises = docs.map((doc) => Promise.resolve(db.post(db)));

  let results = await Promise.all(promises);
  console.log(results);
}
Copy the code