Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么承诺在执行Promise.all()之前得到解决?_Javascript_Promise - Fatal编程技术网

Javascript 为什么承诺在执行Promise.all()之前得到解决?

Javascript 为什么承诺在执行Promise.all()之前得到解决?,javascript,promise,Javascript,Promise,在node.js程序中,我需要在异步收集一些相关数据后,使用POST请求调用API 代码结构基本上如下所示: var promises = []; for(n records in parentRecord.children) { promises.push( getDetails().then( getDetailsOfDetails().then ( httpRequest("POST", collectedDat

在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解决时只解决一次?

尝试类似的方法,它接近于链接承诺的方式

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));

这个问题需要修改。您询问了
getRecord
,但代码中没有
getRecord
。此外,这在语法上是无效的JavaScript。在您显示的代码中没有
getRecord
,而且代码在许多方面在语法上是不正确的。请创建一个。您没有对
然后
使用回调。您正在立即执行下一个代码。它应该是
then(()=>…
。您可以链接承诺而不是嵌套
。then()
方法调用,而
then()
需要一个回调函数,您似乎正在立即调用传递给
的函数。then()
method。我编辑了这个问题,很抱歉弄错了。您可能也想从回调函数调用
updateParentRecord