我有一个承诺链如下:

...

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将需要返回一个函数,该函数将在.then解析时由function2处理程序使用。

07-23 21:17