Javascript 如何在承诺链的中间传递参数?
我有一个承诺链如下:Javascript 如何在承诺链的中间传递参数?,javascript,node.js,promise,Javascript,Node.js,Promise,我有一个承诺链如下: ... 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(); }
...
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))
或者使用
.then(function3.bind(null, id)) // instead of null you can pass some context
否则,function3
将需要返回一个函数,该函数将由使用。然后当function2
解析时,
处理程序将使用该函数。您直接调用function3
,而不考虑链
你必须这样做:
.then(() => function3(id))
// or if you need the response from `function2`
.then(res => function3(id, res))
或者使用
.then(function3.bind(null, id)) // instead of null you can pass some context
否则,function3
将需要返回一个函数,该函数将由使用。然后,function2
解析时,
处理程序将使用该函数。编辑关于修改函数3的注释上方的绑定示例是否明智,以便顺序为不修改答案,不修改答案,修改答案
,我不明白你的意思。移动否则function3需要返回一个函数,该函数将由。然后处理程序在function2解析时使用。
下面一个替代方法是使用.bind…
+1,尽管如果function3
使用function2
的输出,如问题所述(“每个函数都使用从上一个函数返回的结果”),然后它可能看起来像。然后(result=>function3(result,id))
相反。是的,我考虑过,但我不知道function3
是如何定义的,所以我使用了我知道的,第一个参数是id
,因为他调用function3(id)
,不管怎样,如果它确实需要函数2
响应,OP就解决了。我编辑了答案以反映这一点。编辑关于修改函数3的注释上方的绑定示例是否明智,以便顺序是不修改答案,不修改答案,修改答案
?对不起,我不明白你的意思。移动否则,function3将需要返回一个函数,该函数将由.then处理程序在function2解析时使用。
下面的一个替代方法是使用.bind…
+1,但如果function3
使用问题中的function2
输出(“每个都使用从上一个函数返回的结果”),然后它可能看起来像。然后(result=>function3(result,id))
相反。是的,我考虑过,但我不知道function3
是如何定义的,所以我使用了我所知道的,第一个参数是id
,因为他正在调用function3(id)
,无论如何,如果它确实需要function2
响应,OP会找到答案。我编辑了答案以反映这一点。