Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - 等待一项功能完成再继续的正确方法?(Proper way to wait for one function to finish before continuing?)

I have two JS functions.(我有两个JS函数。)

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
        };
    }
};

Is that legit?(那是合法的吗?)

Is there a more elegant way to handle it?(有没有更优雅的处理方式?) Perhaps with jQuery?(也许用jQuery?)   ask by DA. translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!');
    });    
}

As per @Janaka Pushpakumara's suggestion, you can now use arrow functions to achieve the same thing.(按照@Janaka Pushpakumara的建议,您现在可以使用箭头功能实现相同的目的。)

For example:(例如:)

firstFunction(() => console.log('huzzah, I\'m done!'))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...