首页 > 解决方案 > JavaScript:停止执行直到延迟结束

问题描述

我的代码是这样的: -

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
.....
.....

标签: javascriptsettimeout

解决方案


您要么需要使用回调,要么需要使用 Promise。下面是一个 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();

或者,.then()如果您不想使用async/awaitES6 带来的出色功能,可以使用 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.');
});


推荐阅读