为什么在执行Promise.all()之前解决了Promise?

时间:2020-11-03 11:59:37

标签: javascript promise

在node.js程序中,我需要异步收集一些依赖数据后用POST请求调用API。

代码结构基本上是这样的:

var promises = [];
for(n records in parentRecord.children) { 
   promises.push( 
     getDetails().then( 
       getDetailsOfDetails().then ( 
          httpRequest("POST", collectedData).then(
            updateRecord(withNewId)
          )
       )
    )
  );
}

result = Promise.all(promises).then( updateParentRecord(withCollectedResults from HTTP responses) );

问题在于,以getDetails()开头的所有内容都执行了两次,因此发送了n * 2个HTTP请求。 从结构中可以看出,我不是诺言专家。 如何重新构造代码,以便在Promise.all被解决时仅对承诺进行一次解决?

1 个答案:

答案 0 :(得分:1)

尝试类似这样的方法,它与应许承诺的方式非常接近。

var promises = [];
for (n records in parentRecord.children) {
  promises.push(
    getDetails()
    .then(getDetailsOfDetails)
    .then(_ => httpRequest("POST", collectedData))
    .then(_ => updateRecord(withNewId)))
}


result = Promise.all(promises).then(updateParentRecord(withCollectedResults from HTTP responses));
相关问题