JavaScript:停止执行,直到延迟结束 [英] JavaScript: stop execution untill delay is over

查看:50
本文介绍了JavaScript:停止执行,直到延迟结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是这样的:-

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

  • 现在我想要的是,正如您在此处看到的,doStuff() 需要 50 毫秒的时间来执行,因此 doStuff() 之后的代码应该在 doStuff() 完成后执行.例如,该控制台应在 doStuff() 完成后打印.
  • 请注意,我知道我可以将 timeOut 放在那里,但是由于某些限制,我无法设置超时,因为我正在处理一个开源项目,因此我无法更改在该函数调用之后编写的代码,我可以'甚至不等待承诺,因为我告诉我不能更改该代码,我能做的就是更改我制作该方法的 doStuff 方法.有什么方法可以阻止 doStuff() 返回,就像 doStuff() 在延迟结束之前不应该返回,一种方法是我们可以递归调用 doStuff 但我想要更好的方法来做到这一点.请帮帮我.
  • 推荐答案

    您要么需要使用回调,要么需要使用 promise.以下是 Promise 的示例:

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

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

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

    这篇关于JavaScript:停止执行,直到延迟结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆