gpt4 book ai didi

javascript - 将参数传递给 promise 。我必须打破链条吗?

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:59 25 4
gpt4 key购买 nike

我是 nodejs 和 promises 的新手。我需要将参数传递到我的 promise 链中的回调函数。看起来像下面这样:

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

我的 promise 链看起来像

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

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

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

谢谢

最佳答案

将您的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))
}

关于javascript - 将参数传递给 promise 。我必须打破链条吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43008057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com