Javascript 在多个函数完成后运行回调
我有多个耗时的函数,我希望在它们全部完成后运行一个函数,例如:Javascript 在多个函数完成后运行回调,javascript,callback,Javascript,Callback,我有多个耗时的函数,我希望在它们全部完成后运行一个函数,例如: data.x = thisTakes2Seconds(); data.y = thisTakes5Seconds(); http.post(data); 我对Javascript中回调的概念很熟悉,但是如果我有几个函数,我真的应该有多个深层的嵌套回调函数吗?要轻松处理异步函数,最好的方法是使用承诺,和异步/等待 函数thisTakes2Seconds(){ 返回新承诺(resolve=>setTimeout(()=>resolv
data.x = thisTakes2Seconds();
data.y = thisTakes5Seconds();
http.post(data);
我对Javascript中回调的概念很熟悉,但是如果我有几个函数,我真的应该有多个深层的嵌套回调函数吗?要轻松处理异步函数,最好的方法是使用
承诺
,和异步/等待
函数thisTakes2Seconds(){
返回新承诺(resolve=>setTimeout(()=>resolve(3),200));//0.2以避免等待:P
}
函数this耗时5秒(){
返回新承诺(resolve=>setTimeout(()=>resolve(5500));
}
异步函数foo(){
常量数据={};
data.x=等待此时间为2秒();
data.y=等待此操作需要5秒();
//一旦这两个承诺都得到解决,这将运行
控制台日志(数据);
}
foo()
。然后(()=>console.log('done!')
.catch(err=>console.error(err));
我用来处理在几个异步调用执行后执行某些代码的一种技术是使用“has completed”计数器或对象
每个函数都执行一个回调,其中包括
if (counter == numberOfFuntionsIWantedToComplete)
doTheAfterWeHaveAllDataThing`
您的
thisTakesXSeconds
函数将立即返回其结果。这表明它们是同步的。无需回调,该代码只需约7秒即可运行
如果
此TakesxSeconds
启动了一个耗时X秒的异步进程(尽管返回结果的事实表明情况并非如此),我们将研究管理完成进程的方法
我真的应该有多个函数的嵌套回调吗
这个问题,以及对答案“是”的普遍不满,就是为什么我们现在有承诺,甚至有async
functions.:-)
您应该让您的thisTakesXSeconds
函数返回一个承诺,然后在函数可以并行运行的情况下执行以下操作:
Promise.all([
thisTakes2Seconds(),
thisTakes5Seconds()
])
.then(([x, y]) => {
data.x = x;
data.y = y;
// use or return `data` here
})
// return the promise or add a `catch` handler
如果它们需要串联运行(一个接一个),那么
…在async
函数中看起来更清晰一些:
data.x = await thisTakes2Seconds();
data.y = await thisTakes5Seconds();
// use or return `data` here
// add appropriate error handling (at this level or when calling the function)
只有当每个函数都需要完成前一个函数才能执行时,才应该嵌套回调。@NathanInchey,但在本例中,my
http.post
需要完成所有前一个函数(或者数据将不完整),开始使用承诺。使用Promise真的很简单。那么所有的都是。上面的代码看起来是同步的(thisTakesXSeconds
函数返回它们的结果)。无需回调,代码只需约7秒即可运行。
data.x = await thisTakes2Seconds();
data.y = await thisTakes5Seconds();
// use or return `data` here
// add appropriate error handling (at this level or when calling the function)