JavaScript: stop execution untill delay is over

社会主义新天地 提交于 2019-12-13 03:45:45

问题


My code is something like this:-

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
.....
.....
  • Now what I want is, as you can see here that doStuff() takes 50ms of time to execute so the code which is after doStuff() it should execute after doStuff() complete it's work. For example, that console should print after doStuff() is completed.
  • Note that I know I can put timeOut there, but I can't put timeout because of some limitations as I am working on an opensource project so I can't change code which is written after that function call, i can't even wait for promise as i told i can't change that code what I can do is change the doStuff method I have made that method. Is there any way to stop doStuff() return, like doStuff() should not return until that delay is over, one way is we can recursively call doStuff but I want the better way to do that. Please help me out.

回答1:


You either need to use callbacks, or promises. Here's an example of promises:

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();

Alternatively, use .then() of promises, if you don't want to use the nice async/await functionality that ES6 brings:

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.'));

Here's an example of using callbacks:

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


来源:https://stackoverflow.com/questions/51779367/javascript-stop-execution-untill-delay-is-over

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!