在继续之前等待一个功能完成的正确方法? [英] Proper way to wait for one function to finish before continuing?

查看:134
本文介绍了在继续之前等待一个功能完成的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个JS函数。一个叫另一个。在调用函数中,我想调用另一个,等待该函数完成,然后继续。所以,例如/伪代码:

I have two JS functions. One calls the other. Within the calling function, I'd like to call the other, wait for that function to finish, then continue on. So, for example/pseudo code:

function firstFunction(){
    for(i=0;i<x;i++){
        // do something
    }
};

function secondFunction(){
    firstFunction()
    // now wait for firstFunction to finish...
    // do something else
};

我想出了这个解决方案,但不知道这是否是一个聪明的方式去做它。

I came up with this solution, but don't know if this is a smart way to go about it.

var isPaused = false;

function firstFunction(){
    isPaused = true;
    for(i=0;i<x;i++){
        // do something
    }
    isPaused = false;
};

function secondFunction(){
    firstFunction()
    function waitForIt(){
        if (isPaused) {
            setTimeout(function(){waitForIt()},100);
        } else {
            // go do that thing
        };
    }
};

这是合法的吗?是否有更优雅的方式来处理它?也许用jQuery?

Is that legit? Is there a more elegant way to handle it? Perhaps with jQuery?

推荐答案

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

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,我已经完成了!')

这篇关于在继续之前等待一个功能完成的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆