【问题标题】:How to pass argument in middle of promise chain?如何在承诺链中间传递参数?
【发布时间】:2018-11-30 00:03:39
【问题描述】:

我有一个如下的承诺链:

...

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?

【问题讨论】:

    标签: javascript node.js promise


    【解决方案1】:

    你直接调用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 处理程序将使用该函数。

    【讨论】:

    • 编辑上面关于修改函数3的注释的绑定示例是否明智,以便顺序为non modifying answer, not modifying answer, modifying answer
    • 对不起,我没明白你的意思。
    • An alternative is to use .bind...下方移动Otherwise function3 will need to return a function, that will be used by .then handler when function2 resolves.
    • +1,尽管如果function3 使用function2 的输出作为问题(“每个都使用从前一个返回的结果”),那么它可能看起来像.then(result => function3(result, id))
    • 是的,我想过,但我不知道function3 是如何定义的,所以我按照我所知道的,第一个参数是id,因为他打电话给function3(id) , 无论如何,如果它确实需要function2 响应,OP 就知道了。我编辑了答案以反映这一点。
    猜你喜欢
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 2017-12-03
    • 2015-06-06
    相关资源
    最近更新 更多