gpt4 book ai didi

javascript - 在函数中传递多个回调

转载 作者:行者123 更新时间:2023-11-30 07:20:24 24 4
gpt4 key购买 nike

funcOne(cb) {
//some async actions
cb(resp) //pass resp to callback function
}



fucntionTwo(resp) { console.log(resp) }
fucntionThree(resp) { console.log(resp) }

funcOne(funcTwo)
funcOne(funcThree)

在上述情况下,函数 1 将运行两次,如何让 funcOne 运行一次但触发 funcTwo 和 funcThree?我需要从 funcOne 传递响应并执行 funcTwofuncThree表示在funcOne中传递多个回调。

我知道我可以传递多个参数,但还有其他方法吗?

最佳答案

您可以使用 rest parameter语法,然后使用 forEachapply 函数。有点像

function funcOne(...cb) {
console.log("one");
cb.forEach(s => s.apply());
}

function funcTwo() {
console.log("two");
}

function funcThree() {
console.log("three");
}

funcOne(funcTwo, funcThree);

您可以使用任意数量的函数参数调用 funcOne

关于javascript - 在函数中传递多个回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48942259/

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