处理这样的异步工作的一种方法是使用回调函数,例如:
function firstFunction(_callback){
// do some asynchronous work
// and when the asynchronous stuff is complete
_callback();
}
function secondFunction(){
// call first function and pass in a callback function which
// first function runs when it has completed
firstFunction(function() {
console.log('huzzah, I\'m done!');
});
}
根据 @Janaka Pushpakumara 的建议,您现在可以使用箭头函数来实现相同的功能。例如:
firstFunction(() => console.log('huzzah, I\'m done!'))
Update:我很久以前就回答过这个问题,现在真的想更新一下。虽然回调绝对没问题,但根据我的经验,它们往往会导致代码更难以阅读和维护。但在某些情况下我仍然使用它们,例如将进度事件等作为参数传递。此更新只是为了强调替代方案。
另外,最初的问题并没有具体提到异步,因此,如果有人感到困惑,如果您的函数是同步的,那么它will调用时阻塞。例如:
doSomething()
// the function below will wait until doSomething completes if it is synchronous
doSomethingElse()
如果正如所暗示的那样,该函数是异步的,那么我今天处理所有异步工作的方式就是使用 async/await。例如:
const secondFunction = async () => {
const result = await firstFunction()
// do something else here after firstFunction completes
}
IMO,async/await 使您的代码比直接使用 Promise(大多数时候)更具可读性。如果您需要处理捕获错误,请将其与 try/catch 一起使用。在这里阅读更多内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function .