【问题标题】:Passing arguments into promises. Do I have to break the chain?将参数传递到 Promise 中。我必须打破链条吗?
【发布时间】:2017-08-17 21:31:39
【问题描述】:

我是 nodejs 和 promises 的新手。我需要将参数传递给我的承诺链中的回调函数。如下所示:

var first = function(something) {
/* do something */
return something.toString();
}
var second = function(something, item) {
/* need to work with both the args */
}

我的承诺链看起来像

function(item) {
    /* the contents come from first callback and the item should be passed as an argument to the second callback */
    fs.readFile(somefile).then(first).then(second)
}

我应该将项目作为参数传递,我可以这样做而不破坏我的链条吗?

如果我完全错了,请纠正我。

谢谢

【问题讨论】:

    标签: javascript node.js typescript promise


    【解决方案1】:

    将您的second 函数包装成一个匿名函数并以这种方式传入参数:

    function(item) {
        /* the contents come from first callback and the item should be passed as an argument to the second callback */
        fs.readFile(somefile)
            .then(first)
            .then(firstResult => second(firstResult, item))
    }
    

    【讨论】:

    • 这不是我的选择。我将不得不为每一行代码编写测试。
    【解决方案2】:

    您可以使用 Function.prototype.bind() 将项目传递给第二个函数

     fs.readFile(somefile).then(first)
    .then(second.bind(null, item))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-01
      • 2019-01-04
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2015-04-18
      • 2023-03-16
      • 2016-03-27
      相关资源
      最近更新 更多