承诺可以在节点中转发

时间:2016-04-21 11:26:20

标签: javascript node.js asynchronous promise q

我有以下要求,我有三个异步函数async1(),async2(),ascync3()都返回promises 现在我将调用一个函数并分别串行执行async1,async2,async3,我想打印async3后返回的已解析的promise

这是我的主要功能

testPromiseSerially = function() {
  return new promise(function(resolve,reject) {
   async1().
   then(function(result1) {
    return async2(result1)
   })
   .then(function(result2){
     return async3(result2)
   })
   .catch(function(err) {
     return reject(err) 
   }
 })
}

这是我的async3功能

async3 = function(params) {
 return new promise(function(resolve,reject) {
   return resolve("solved")
})
}

和async1和async2也类似于async3

如果我执行此代码

testPromiseSerially.then(function(result) {
  console.log(result)
})
.catch(function (err) {
 console.log(err) 
})

testPromiseSerially正在调用,但它没有进入'then'或'catch' block.is承诺返回async3没有中继回testpromiseSerially()? 如何查看async3的结果?  我知道,如果我扩展我的代码,如添加

.then(function(result) {
  return resolve(result)
})

在async3(结果)之后,我将能够看到结果。但是我有一系列依赖于其他函数返回的promise的函数,所以我该如何处理呢?

2 个答案:

答案 0 :(得分:3)

主要问题是您的testPromiseSerially代码永远不会调用resolve。所以它返回的承诺永远不会得到解决。

由于它已经已经承诺了的承诺,因此您无需创建新的。每次调用then都会产生新的承诺,所以只需使用它。

此外,这:

.then(function(result1) {
    return async2(result1);
})

比你需要的更复杂/更冗长,它可以只是:

.then(async2)

同样适用于.catch

所以:

let testPromiseSerially = function() {
  return async1()
      .then(async2)
      .then(async3);
};

Example using JavaScript's native promises on Babel's REPL

答案 1 :(得分:0)

您应该使用异步https://github.com/caolan/async。对你的情况更好。看看瀑布功能。

来自文档

waterfall(tasks, [callback])

Runs the tasks array of functions in series, each passing their results to the next in the array. However, if any of the tasks pass an error to their own callback, the next function is not executed, and the main callback is immediately called with the error.