简体   繁体   English

如何在承诺链中间传递论点?

[英]How to pass argument in middle of promise chain?

I have a promise chain as follows: 我有一个诺言链如下:

...

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();
    });

...

Where function1, function2, function3, and function4 need to be called in order and each uses the result returned from the previous. 需要依次调用function1,function2,function3和function4,并且每个函数都使用前一个返回的结果。 The problem I am running into is that function3 requires the id parameter, but whenever I set it as shown above then the result from function3 is not passed to function4. 我遇到的问题是function3需要id参数,但是每当我如上所述设置它时,function3的结果就不会传递给function4。 How do I pass the id parameter to function3 and pass the result from function3 to function4? 如何将id参数传递给function3 并将结果从function3传递给function4?

You're calling function3 directly, without respecting the chain. 您是在直接调用function3而不遵循链。

You have to do it this way: 您必须这样做:

.then(() => function3(id))
// or if you need the response from `function2`
.then(res => function3(id, res))

Or an alternative is to use .bind 或替代方法是使用.bind

.then(function3.bind(null, id)) // instead of null you can pass some context

Otherwise function3 will need to return a function, that will be used by .then handler when function2 resolves. 否则, function3将需要返回一个函数,当function2解析时, .then处理程序将使用该function2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM