node.js - promise中第3个then分别用第一个和第二个then返回的参数该如何写呢?

查看:647
本文介绍了node.js - promise中第3个then分别用第一个和第二个then返回的参数该如何写呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

testObject

.func1()
.then((result)=>{
    return r1;
})
.then((result1)=>{
    return r2;
})
.then((result2)=>{
    func(r1,r2);
})

请问如果要实现这样的逻辑该如何呢?
阮一峰的原文如下:

then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...
});
上面的代码使用then方法,依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。

似乎只是一层一层的传递参数,请问如何将1,2的then传递给3呢,或者一次性传递2个参数。

解决方案

Promise.all

var promise = Promise.resolve(3);
Promise.all([true, promise])
  .then(values => {
    console.log(values); // [true, 3]
  });

https://developer.mozilla.org...

这篇关于node.js - promise中第3个then分别用第一个和第二个then返回的参数该如何写呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆