JavaScript:停止执行直到延迟结束

时间:2018-08-10 05:13:10

标签: javascript settimeout

我的代码是这样的:-

function doStuff(){
    // Note:- this funcion take 50ms for ececution as i have put 
    // timeout
    setTimeout(function(){ 
        // some line of code
        ....
    }, 50);

    return;
}
doStuff();
console.log('This should execute after doStuff() complete its work.")
// after that more many lines of code and more stuff are here
.....
.....
  • 现在我想要的是,正如您在这里看到的,doStuff()需要50毫秒的时间来执行,因此doStuff()之后的代码应该在doStuff()完成工作后才执行。例如,该控制台应在doStuff()完成后打印。
  • 请注意,我知道我可以将timeOut放置在那里,但是由于某些限制,我无法放置超时,因此我无法更改在该函数调用之后编写的代码,因此我不能我什至无法等待诺言,因为我告诉我无法更改该代码,我只能更改已创建的doStuff方法。有什么方法可以阻止doStuff()返回,就像doStuff()在延迟结束之前不应该返回一样,一种方法是我们可以递归调用doStuff,但我希望有更好的方法来做到这一点。请帮帮我。

1 个答案:

答案 0 :(得分:2)

您需要使用回调或Promise。这是一个诺言的例子:

function doStuff(){
    var promise = new Promise((resolve) => {
    
      // Note:- this funcion take 50ms for ececution as i have put 
      // timeout
      setTimeout(function(){ 
          // some line of code
          resolve();
      }, 1000);
    });

    return promise;
}

async function main() {
  console.log('Start.');
  await doStuff();
  console.log('This should execute after doStuff() complete its work.');
}

main();

或者,如果您不想使用ES6带来的不错的.then()功能,请使用async/await的Promise:

function doStuff(){
    var promise = new Promise((resolve) => {
    
      // Note:- this funcion take 50ms for ececution as i have put 
      // timeout
      setTimeout(function(){ 
          // some line of code
          resolve();
      }, 1000);
    });

    return promise;
}

console.log('Start.');
doStuff().then(() => console.log('This should execute after doStuff() complete its work.'));

这是使用回调的示例:

function doStuff(callback){
    setTimeout(function(){ 
        // some line of code
        callback();
    }, 1000);
}

console.log('Start.');
doStuff(function() {
  console.log('This should execute after doStuff() complete its work.');
});