JS:承诺链中的setTimeout如何工作?

问题描述 投票:-1回答:1

下面的代码在进入下一个then()之前会等待记录“ A”吗?我似乎可靠地取回了在“ B”之前记录的“ A”,即使它指定了更长的超时时间。

     .then((response) => {
        setTimeout(() => {
            console.log("A");
        }, 1000)
        this.doSomething();
    }).then(() => {
        setTimeout(() => {
            console.log("B");
        },  800)
    })
javascript
1个回答
0
投票

setTimeout()是非阻塞的,因此代码总是立即进行,并且超时内的内容将在以后的某个时间发生。因此,在您的情况下:

     .then((response) => {
        // The timeout is *set* immediately without blocking
        setTimeout(() => {
            // This happens about a second from now
            console.log("A");
        }, 1000)
        // This happens immediately after *setting* the timeout.
        // The stuff inside that timeout happens *later*
        this.doSomething();
    }).then(() => {
        setTimeout(() => {
            console.log("B");
        },  800)
    })

如果要向链中添加超时,则需要使用promise的东西。例如:

function wait (seconds){
  // This promise will resolve after the number of seconds specified
  return new Promise(res=>{
    setTimeout(res,seconds*1000);
  });
}

您在逻辑链中的适应方式取决于您要执行的操作。如果您正在履行承诺,请一定要查看async/await。它使一切变得简单!

© www.soinside.com 2019 - 2024. All rights reserved.