将节点异步代码转换为promise

Converting node async code to promises

本文关键字:promise 转换 代码 节点 异步      更新时间:2023-09-26

我正在尝试promise,即when.js,并希望转换一些测试代码,即使在阅读文档后也不清楚如何转换。到目前为止,我的实验比标准的回调金字塔要混乱得多,所以我想我错过了一些捷径。

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

Async1(function(err, res) {
  res++;
  Async2(res, function(error, result) {
    done();
  })
})
nodefn.call(Async2, nodefn.call(Async1)).ensure(done);

在这里,Async2实际上是同步调用的,并以Async1()的Promise作为参数——它不等待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);

我想在两个调用之间执行一些逻辑

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

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

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

// One time configuration of promise versions
async1 = promisify(async1);
async2 = promisify(async2);
// construct flow
async1().then(function (res) { return async2(++res); }).done();