我有两个同时运行的函数,我希望回调在最后一个函数完成时只执行一次。
function gotoPage () {
//only call this once for the last one
}
app.update(gotoPage);
geolocation.getCurrentPosition(gotoPage);
我意识到我可以嵌套它们以顺序执行,但出于性能原因我不想这样做。 有没有一个巧妙的技巧可以有效地做到这一点?
最佳答案
通过 promise 解决:
Promise.all([
new Promise(resolve => app.update(resolve)),
new Promise(resolve => geolocation.getCurrentPosition(resolve)),
]).then(() => gotoPage());
您可以在此处阅读 Promise:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
关于javascript - 一个 onComplete 回调用于执行两个函数中的最后一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49560218/