跟踪是否已执行两个功能

时间:2020-05-19 14:27:59

标签: javascript

我有两个职能。 funcAfuncB。我想跟踪两个都执行的时间。

所以我有这个代码:

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...');

仅当两个功能均已执行时,我想查看控制台日志。

1 个答案:

答案 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"]
使用Promise。,您对JS的所有说法只有在所有Promise(在您的情况下为函数)都已解决时才继续。

您可以在MDN

中找到更多信息