我有两个职能。 funcA
和funcB
。我想跟踪两个都执行的时间。
所以我有这个代码:
let addExecuted = 0;
function bothFunctionsExecuted(){
addExecuted++
if(addExecuted === 2){
// Both functions executed so console log it
addExecuted = 0; // set this to initial state
console.log('Both functions executed...');
}
};
然后,我可以在每个函数中执行bothFunctionsExecuted()
。但说实话,这不是一个好的解决方案,因为如果其中一个函数执行两次,我仍然可以看到console.log('Both functions executed...');
仅当两个功能均已执行时,我想查看控制台日志。
答案 0 :(得分:0)
使用Promises,这是一个如何使用Promise的示例(您的函数必须最后运行resolve()
)
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
// expected output: Array [3, 42, "foo"]
您可以在MDN
中找到更多信息