简体   繁体   English

在Promise.all内部使用其他同步功能是否有优势?

[英]Is there an advantage to using an otherwise synchronous function inside a Promise.all?

Say I have a synchronous function like this: 说我有一个这样的同步功能:

function sumTotal(items) {
  return items.reduce((total, item) => item.price + total)
}

And it is used after a Promise.all containing some asynchronous API calls within this 'checkout' function 它在Promise.all之后使用,所有“ checkout”函数中包含一些异步API调用

function checkout(items) {
  return Promise.all([
    getLatestOffers(),
    getCustomerDetails('johndoe@gmail.com')
  ]).then(([offers, details]) => {
    return { offers, details, total: sumTotal(items) }
  });
}

Is there be any advantage, performance wise or other, to changing the sumTotal function to return a promise and calling it in the Promise.all like this? 无论是性能方面还是其他方面,更改sumTotal函数以返回一个Promise.Promise.all都可以有什么好处?

function checkOut(items) {
  return Promise.all([
    getLatestOffers(),
    getCustomerDetails('johndoe@gmail.com'),
    sumTotal(items)
  ]).then(([offers, details, total]) => {
    return { offers, details, total }
  });
}

Either method works. 两种方法均有效。 Because sumTotal is synchronous, it won't matter in most cases. 因为sumTotal是同步的,所以在大多数情况下都没有关系。 The only time it might matter is if items is an unreasonably huge array, and iterating over it takes a not-insignificant amount of CPU time - in which case, it would be better to call sumTotal with Promise.all so that it can resolve immediately once the promises resolve, rather than having to wait for an expensive operation after the other promises resolve. 可能事情的唯一情况是如果items是不合理的庞大的阵列,并遍历它需要CPU时间的不可忽略量-在这种情况下,倒不如叫sumTotalPromise.all以便它能够立即解决一旦承诺达成,而不必在其他承诺解决等待昂贵的操作。

But, keep in mind that Promise.all accepts non-Promises as well: there's no need to convert sumTotal to something that returns a Promise . 但是,请记住, Promise.all接受非Promise :无需将sumTotal转换为返回Promise

Also, if items is an array of objects with a price property, make sure to provide reduce with an initial value, else you might end up with something like [Object object]102030 for your total : 另外,如果items是具有price属性的对象数组,请确保提供具有初始值的reduce ,否则您的total可能会类似于[Object object]102030

 const somethingAsync = () => new Promise(res => setTimeout(res, 500, 'foo')); function sumTotal(items) { return items.reduce((total, item) => item.price + total, 0) } function checkOut(items) { return Promise.all([ somethingAsync(), somethingAsync('johndoe@gmail.com'), sumTotal(items) ]).then(([offers, details, total]) => ( { offers, details, total } )); } console.log('start'); checkOut([{ price: 10 }, { price: 20 }]) .then(output => console.log(output)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM