gpt4 book ai didi

javascript回调多个函数之间的混淆

转载 作者:行者123 更新时间:2023-12-01 03:55:11 25 4
gpt4 key购买 nike

function A(){
b()
c()
}

函数 c 必须在函数 b 之后调用。我知道 JavaScript 中有一个概念叫做回调。

如何在函数 b 中执行此操作?

function b(cb){
//I can't put function c here, because this of c is bound to somewhere and I don't want to mess up.
}

最佳答案

c() 将始终在 b() 之后调用,因为您将其放置在那里。

真正的问题是在 b() 完成之前是否会调用 c()

如果b()不是异步函数,那么您的代码就是完美的。 b() 完成后将调用 c()

function A(){
b(); // *not* async
c();
}

但是,如果 b() 本质上是异步的,则需要提供 c() 作为回调。 函数A(){ 公元前);//异步 }

function b(cb){
// ...
cb(); // cb() doesn't need "this"
}

由于 c() 是绑定(bind)方法,因此您还需要将上下文 (this) 传递给 b()

function A(){
/* extract and save context, somehow */
b(c, context); // async
}

function b(cb, context){
// ...
cb.call(context); // cb() doesn't need "this"
}

I don't want to mess up.

如果您不想使用上下文传递,可以使用 Promise .

function A(){
b().then(function() {
// run "c()" only when "b()" is finished and there were no errors
c();
});
}

function b(){
// ...
// "b()" is *not* async
return Promise.resolve();
}

function b(){
// ...
// "b()" is async
var whenDone = new Promise(function(resolve, reject) {
performAsyncTask(resolve);
})
return whenDone;
}

但是等等,还有更多。

如果您想要尖端技术,您可以随时使用async/await

async function A(){
await b(); // VOILA! it's that easy
c();
}
<小时/>

这些是一般的基本策略。当然,您可以尝试混合搭配它们或尝试找出适合您需求的新东西。

关于javascript回调多个函数之间的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42825246/

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