且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在继续之前等待一个功能完成的正确方法?

更新时间:2022-02-01 00:15:42

处理这样的异步工作的一种方法是使用回调函数,例如:

One way to deal with asynchronous work like this is to use a callback function, eg:

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的建议,你现在可以使用箭头功能来实现同样的目的。例如:


As per @Janaka Pushpakumara's suggestion, you can now use arrow functions to achieve the same thing. For example:

firstFunction(()=> console.log('huzzah,我已经完成了!')