setTimout() 代码完成后同步执行代码的简单方法 [英] Simple way to synchronously execute code after setTimout() code is done

查看:57
本文介绍了setTimout() 代码完成后同步执行代码的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种简单的方法来等待 setTimeout 代码完成执行,然后运行 ​​setTimeout 之后的代码.现在包含 setTimout 的循环之后的代码在 loop/setTimout 执行完成之前执行.

I need a simple way to wait for setTimeout code to finish executing and then run the code that comes after setTimeout. Now the code after loop containing setTimout is executing before loop/setTimout is finished executing.

for(let i = 0; i < 5; i++) {
   setTimeout(function(){
    console.log(i);
  }, i*1000);
 }
console.log("loop/timeout is done executing");

推荐答案

setTimeout 根据定义是非同步的 - 无论您使用什么来解决问题,都必须是异步的,没有办法解决这个问题.

setTimeout is by definition not synchronous - whatever you use to solve the issue will have to be asynchronous, there's no way around that.

实现这样的事情的最好方法是使用 Promise 代替,在创建的承诺数组上调用 Promise.all :

The best way to achieve something like this is to use Promises instead, calling Promise.all on an array of the created promises:

(async () => {
  await Promise.all(Array.from(
    { length: 5 },
    (_, i) => new Promise(res => setTimeout(() => {
      console.log(i);
      res();
    }, i * 1000))
  ));
  console.log("loop/timeout is done executing");
})();

虽然 await 正在等待一个 Promise,而 Promises 不是同步的,但如果您希望代码 看起来 扁平化以便您可以拥有最终的 console.log 与主功能块在同一缩进级别,这可能是要走的路.

Although await is awaiting a Promise, and Promises aren't synchronous, if you're want the code to look flat so you can have the final console.log on the same indentation level as the main function block, this is probably the way to go.

这篇关于setTimout() 代码完成后同步执行代码的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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