我正在尝试 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);
I want to perform some logic between the 2 calls
然后您需要在链中放置另一个函数,或者修改链中的函数之一:
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);
关于javascript - 将 Node 异步代码转换为 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17453488/