将节点异步代码转换为promises

时间:2013-07-03 16:35:49

标签: javascript node.js promise when-js

我正在试验承诺 - 即when.js - 并希望转换一些测试代码 - 有点不清楚即使在阅读文档之后该怎么做。到目前为止,我的实验比标准的回调金字塔更加混乱,所以我想我错过了一些捷径。

这是我想要复制的示例代码:

Async1(function(err, res) {
  res++;
  Async2(res, function(error, result) {
    done();
  })
})

2 个答案:

答案 0 :(得分:3)

nodefn.call(Async2, nodefn.call(Async1)).ensure(done);

在这里,Async2实际上是同步调用的,并且Async1()的承诺作为参数 - 它不等待Async1解析。要链接它们,您需要使用

nodefn.call(Async1).then(nodefn.lift(Async2)).ensure(done);
// which is equivalent to:
nodefn.call(Async1).then(function(result) {
    return nodefn.call(Async2, result);
}).ensure(done);
  

我想在2个电话之间执行一些逻辑

然后你需要在链中放入另一个函数,或者修改链中的一个函数:

nodefn.call(Async1)
  .then(function(res){return res+1;}) // return modified result
  .then(nodefn.lift(Async2))
  .ensure(done);
// or just
nodefn.call(Async1).then(function(res) {
    res++; // do whatever you want
    return nodefn.call(Async2, res);
}).ensure(done);

答案 1 :(得分:1)

不确定何时使用Deferred库,你可以这样做:

// One time configuration of promise versions
async1 = promisify(async1);
async2 = promisify(async2);

// construct flow
async1().then(function (res) { return async2(++res); }).done();
相关问题