Javascript 将节点异步代码转换为承诺
我正在试验承诺-即when.js-并希望转换一些测试代码-即使在阅读文档后也不清楚如何转换。到目前为止,我的实验比标准的回调金字塔要混乱得多,所以我想我错过了一些捷径 下面是我要复制的示例代码:Javascript 将节点异步代码转换为承诺,javascript,node.js,promise,when-js,Javascript,Node.js,Promise,When Js,我正在试验承诺-即when.js-并希望转换一些测试代码-即使在阅读文档后也不清楚如何转换。到目前为止,我的实验比标准的回调金字塔要混乱得多,所以我想我错过了一些捷径 下面是我要复制的示例代码: Async1(function(err, res) { res++; Async2(res, function(error, result) { done(); }) }) 在这里,Async2实际上是被同步调用的,并承诺将Async1()作为一个参数-它不会等待Async1解析。
Async1(function(err, res) {
res++;
Async2(res, function(error, result) {
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);
我想在两个调用之间执行一些逻辑
然后需要在链中放置另一个函数,或修改链中的一个函数:
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);
在这里,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);
我想在两个调用之间执行一些逻辑
然后需要在链中放置另一个函数,或修改链中的一个函数:
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);
不确定何时使用库,但您可以这样做:
// One time configuration of promise versions
async1 = promisify(async1);
async2 = promisify(async2);
// construct flow
async1().then(function (res) { return async2(++res); }).done();
不确定何时使用库,但您可以这样做:
// One time configuration of promise versions
async1 = promisify(async1);
async2 = promisify(async2);
// construct flow
async1().then(function (res) { return async2(++res); }).done();
制定
Async1().then(函数(res){return Async2(res+1)}.then(done)
或调整Async
函数时有问题吗?然后您需要向我们展示他们的代码…我有nodefn.call(Async2,nodefn.call(Async1))。确保(完成);但是我不确定我会在哪里做res++-它实际上只是一个占位符-我想在两个调用之间执行一些逻辑。您在制定Async1().然后(函数(res){return Async2(res+1)})时有问题吗?然后(完成)
或者调整Async
函数?然后您需要向我们展示他们的代码…我有nodefn.call(Async2,nodefn.call(Async1))。确保(完成);但我不确定在哪里执行res++-它实际上只是一个占位符-我想在两个调用之间执行一些逻辑