JavaScript承诺。然后,设置超时顺序

JavaScript承诺。然后,设置超时顺序,javascript,promise,Javascript,Promise,getAllUsers():void{ this.allUsers=this.userService.getUsers() .然后(res=>this.alluser=res) 。然后(()=>设置超时(()=> this.allUsers.forEach(user=>console.log(user)),2000 )) .然后(()=>setTimeout(this.restOfInit(),4000)) .catch((错误)=>console.log(错误)); //console.log

getAllUsers():void{
this.allUsers=this.userService.getUsers()
.然后(res=>this.alluser=res)
。然后(()=>设置超时(()=>
this.allUsers.forEach(user=>console.log(user)),2000
))
.然后(()=>setTimeout(this.restOfInit(),4000))
.catch((错误)=>console.log(错误));
//console.log(this.alluser[0]);
//setTimeout(()=>console.log(this.allUsers[0]),3000);
}
两件事:

1) 传递给
setTimeout()
的函数大约在指定的毫秒数内异步执行。你可能知道这一点。但是,对
setTimeout()
的调用(几乎立即)返回,而不考虑指定的时间

2) 您希望传递
this.restOfInit
而不是
this.restOfInit()
。前者将函数传递给
setTimeout()
。后者调用函数时不带参数,并将返回值(可能
未定义
)传递给setTimeout()

tldr

.then(() => setTimeout(this.restOfInit(), 4000)) // Change this line

.then(() => setTimeout(this.restOfInit, 4000))  // to this

正如@fvgs所正确指出的,您看到的触发顺序的问题在于立即调用this.restOfInit——它的返回值被传递到
setTimeout
,而不是函数本身

然而,在这里使用超时违背了承诺的意义。承诺应该允许您精确地安排订单,并将尽可能快地执行,而不是保证等待时间,无论您对用户的请求有多快。实际上,您的回调根本不需要链接,因为只有第一个回调需要解析值。这样安排会容易得多

    getAllUsers(): void {
      this.userService.getUsers()
        .then(res => {
          this.allUsers = res
          this.allUsers.forEach(user => console.log(user))
          this.restOfInit()
        })
        .catch((error) => console.log(error)));
    }
另请注意-分配
this.allUsers=this.userService.getUsers()
链将是一个承诺,但在回调中分配
this.allUsers=res
,从外观上看,它将是一个数组。我怀疑这可能是您使用
setTimeout
的原因,因为它可能会在您不期望的情况下覆盖它


除非您需要进一步与承诺链交互,否则没有必要使用
this.allUsers=this.userService.getUsers()
,因此我在上面的代码中省略了这一点
this.restOfInit(),4000
删除括号。对,我知道1),但2)解释了问题,显然,应该发送函数,而不是立即调用。谢谢你指出!啊,我明白了。谢谢,那很有帮助。