[英]How to pass argument in middle of promise chain?
我有一个诺言链如下:
...
const id = "someId";
function1(id)
.then(function2)
.then(function3(id))
.then(function4)
.then(result => {
res.status(200).send(result);
})
.catch(error => {
res.status(500).end();
});
...
需要依次调用function1,function2,function3和function4,并且每个函数都使用前一个返回的结果。 我遇到的问题是function3需要id参数,但是每当我如上所述设置它时,function3的结果就不会传递给function4。 如何将id参数传递给function3 并将结果从function3传递给function4?
您是在直接调用function3
而不遵循链。
您必须这样做:
.then(() => function3(id))
// or if you need the response from `function2`
.then(res => function3(id, res))
或替代方法是使用.bind
.then(function3.bind(null, id)) // instead of null you can pass some context
否则, function3
将需要返回一个函数,当function2
解析时, .then
处理程序将使用该function2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.