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

2024-03-16

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

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

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

我想出了这个解决方案,但不知道这是否是一个明智的方法。

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?


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

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 .

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在继续之前等待一个函数完成的正确方法? 的相关文章

随机推荐