Promise.all() 和并行承诺在节点上有所不同 [英] Promise.all() and parallel promises are they differ in node

查看:17
本文介绍了Promise.all() 和并行承诺在节点上有所不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我可以通过两种方式实现我的代码来发出 axios 请求

I have a scenario where I can implement my code to make axios requests in two ways

const data = {};

try {

  if (searchArray.includes('address')) {
    const address = await axios('./getAddress')
    data.addresses = address.data;
  }

  if (searchArray.includes('email')) {
    const email = await axios('./email')
    data.emails = email.data;
  }

  if (searchArray.includes('phone')) {
    const phoneNumber = await axios('./phone')
    data.phoneNumbers = phoneNumber.data;

  }
} catch (err) {
  return res.status(constants.HTTP_SERVER_ERROR).json(err);
}

res.status(200).json(data);

const data = {};
const promises = []

if (searchArray.includes('address')) {
  promises.push(axios('./getAddress'))
}

if (searchArray.includes('email')) {
  promises.push(axios('./email'))
}

if (searchArray.includes('phone')) {
  promises.push(axios('./phone'))
}

Promise.all(promises)
  .then(results => {
    res.status(200).json(results);
  })
  .catch(err) {
    return res.status(constants.HTTP_SERVER_ERROR).json(err);
  }

哪种方法更好?为什么?

Which is the better approach? and why?

我更喜欢第一种方法,因为与完整的结果数组相比,我可以拥有结构良好的数据.但是得到了顺序实施而不是并行实施的建议

I prefer 1st approach because I can have well structured data than complete array of results. But got suggestion to implement sequentially than parallel

我假设 node 是单线程的,所以在实现它时没有发现任何区别(如果我使用 async 和 await,我可能是错的)

I assume node is single threaded so didn't find any difference in implementing it (I might be wrong if I use async and await)

推荐答案

第二种方法的性能会更好.

The second approach will be more performant.

在第一个示例中,假设每个请求需要 1 秒才能返回,因此在等待一个请求的结果后再进行下一个请求时,您至少需要 3 秒以上的时间来返回结果.

In the first example assume that each request takes 1 second to return, so you will take at least 3+ seconds to return your results as you wait for the result of one request before making the next.

在第二种方法中,您一次发出所有请求,然后等待 IO 回调.处理完所有请求后,Promise.all() 将解析.如果每个请求需要大约 1 秒但并行发出,则您的响应也将大约为 1 秒.

In the second approach you make all the requests at once, and then wait for the IO callback. Once all the requests are handled the Promise.all() will resolve. If each request takes ~1 sec but is made in parallel your response will be about 1 second as well.

我会使用如下语法来保持可读性,因为您似乎在使用 async/await 并且不需要引用 promises.

I would use syntax like the following however to maintain readability as you seem to be using async/await and don't need to have a reference to the promises.

try {
  const [addresses, emails, phones] = await Promise.all([
    searchArray.includes('address') 
      ? axios('./getAddress') : Promise.resolve({}),
    searchArray.includes('email') 
      ? axios('./email') : Promise.resolve({}),
    searchArray.includes('phone') 
      ? axios('./phone') : Promise.resolve({}),
  ]);
  return res.status(200).json({
     addresses: addresses.data,
     emails: emails.data,
     phoneNumbers: phones.data,
  });
} catch (err) {
  return res.status(constants.HTTP_SERVER_ERROR).json(err);
}

这篇关于Promise.all() 和并行承诺在节点上有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆