Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.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 承诺。全部()然后()解决?_Javascript_Node.js_Promise - Fatal编程技术网

Javascript 承诺。全部()然后()解决?

Javascript 承诺。全部()然后()解决?,javascript,node.js,promise,Javascript,Node.js,Promise,使用Node 4.x。当您有一个Promise.all(promises).then()解析数据并将其传递给下一个。then()的正确方法是什么 我想这样做: Promise.all(promises).then(function(data){ // Do something with the data here }).then(function(data){ // Do more stuff here }); 但是我不知道如何将数据发送到第二个。then()。我不能在第一个中使用解析

使用Node 4.x。当您有一个
Promise.all(promises).then()
解析数据并将其传递给下一个
。then()
的正确方法是什么

我想这样做:

Promise.all(promises).then(function(data){
  // Do something with the data here
}).then(function(data){
  // Do more stuff here
});
但是我不知道如何将数据发送到第二个
。then()
。我不能在第一个
中使用
解析(…)
。然后()。我想我能做到这一点:

return Promise.all(promises).then(function(data){
  // Do something with the data here
  return data;
}).then(function(data){
  // Do more stuff here
});
但这似乎不是正确的方法。。。正确的方法是什么

但这似乎不是正确的方法

这确实是正确的做法(或者至少是正确的做法)。这是承诺的一个关键方面,它们是一个管道,管道中的各种处理程序可以对数据进行处理

例如:

const承诺=[
新承诺(resolve=>setTimeout(resolve,0,1)),
新承诺(resolve=>setTimeout(resolve,0,2))
];
所有(承诺)
。然后(数据=>{
log(“第一个处理程序”,数据);
返回data.map(entry=>entry*10);
})
。然后(数据=>{
log(“第二个处理程序”,数据);

});如今,NodeJS支持新的
async/await
语法。这是一个简单的语法,使生活更容易

async function process(promises) { // must be an async function
    let x = await Promise.all(promises);  // now x will be an array
    x = x.map( tmp => tmp * 10);              // proccessing the data.
}

const promises = [
   new Promise(resolve => setTimeout(resolve, 0, 1)),
   new Promise(resolve => setTimeout(resolve, 0, 2))
];

process(promises)
了解更多信息:


您的
返回数据的方法是正确的,这就是一个示例。如果从
.then()
回调返回承诺,JavaScript将解析该承诺并将数据传递给下一个
then()
回调


只要小心,确保使用
.catch()
处理错误

有趣。非常感谢。因此,在初始的
Promise
函数之后,是否不可能
拒绝
值?或者在链中的任何位置抛出错误会将您带到
.catch()
?如果是这样的话,
拒绝
首先有什么意义?为什么不直接抛出错误呢?再次感谢,@JakeWilson:这些是不同的问题。但是你混淆了两件不同的事情:创造和解决承诺,以及处理承诺。创建和结算承诺时,使用
resolve
reject
。在处理时,如果处理失败,确实会抛出异常以触发失败路径。是的,您也可以从原始的
Promise
回调抛出异常(而不是使用
reject
),但并非所有的失败都是异常。我如何从进程向每个单独的Promise传递参数?@阿米纳达夫·格利克施泰因