Call async/await functions in parallel

匿名 (未验证) 提交于 2019-12-03 03:08:02

问题:

As far as I understand, in ES7/ES2016 putting multiple await's in code will work similar to chaining .then() with promises, meaning that they will execute one after the other rather than in parallerl. So, for example, we have this code:

await someCall(); await anotherCall();

Do I understand it correctly that anotherCall() will be called only when someCall() is completed? What is the most elegant way of calling them in parallel?

I want to use it in Node, so maybe there's a solution with async library?

EDIT: I'm not satisfied with the solution provided in this question: Slowdown due to non-parallel awaiting of promises in async generators, because it uses generators and I'm asking about a more general use case.

回答1:

You can await on Promise.all():

await Promise.all([someCall(), anotherCall()]);


回答2:

Combine the result into one line code (plus, concat, or any other function you like) could also do such trick:

const someResult = someCall(); const anotherResult = anotherCall(); const finalResult = [await someResult, await anotherResult] //later you can use the result with variable name.

JSbin example: http://jsbin.com/wiqorinowi/1/edit?js,console



回答3:

Just make sure you call both functions before you await either one:

// Call both functions const somePromise = someCall(); const anotherPromise = anotherCall();  // Await both promises     const someResult = await somePromise; const anotherResult = await anotherPromise;


回答4:

I create a helper function parallel, may be it can make it sweeter

const parallel = async (...items) => {     //doesn't work     // return items.map(async (p) => {     //     return await p;     // });      // works     const temp = [];     for (const item of items) {         temp.push(await item);     }     return temp; };  const finalResult = await parallel(someResult(), anotherResult()); //or //const [result1, result2] = await parallel(someResult(), anotherResult());


回答5:

I vote for:

await Promise.all([someCall(), anotherCall()]);

Be aware of the moment you call functions, it may cause unexpected result:

// Supposing anotherCall() will trigger a request to create a new User  if (callFirst) {   await someCall(); } else {   await Promise.all([someCall(), anotherCall()]); // --> create new User here }

But following always triggers request to create new User

// Supposing anotherCall() will trigger a request to create a new User  const someResult = someCall(); const anotherResult = anotherCall(); // ->> This always creates new User  if (callFirst) {   await someCall(); } else {   const finalResult = [await someResult, await anotherResult] }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!