简体   繁体   English

使用 Promise 链实现详细的睡眠功能

[英]Implementing a verbose sleep function using a chain of Promises

I am trying to implement a sleep function using Promises in JavaScript.我正在尝试使用 JavaScript 中的 Promise 实现睡眠功能。

function sleep(ms) {

  var begin = new Promise(resolve => {
    console.log("Sleep function called for " + ms + " ms\n")
  });

  return new Promise(resolve => setTimeout(resolve, ms))
    .then(() => console.log("Sleep done!" ));

}

and it works.它有效。 But,但,

function sleep(ms) {

  var begin = new Promise(resolve => {
    console.log("Sleep function called for " + ms + " ms\n")
  });

  return begin.then(resolve => setTimeout(resolve, ms))
    .then(() => console.log("Sleep done!" ));

}

doesn't, rather it just hangs!没有,而是挂起! What gives?是什么赋予了?

UPDATE : What I really want to do is write it out as a sequence of promise calls.更新:我真正想做的是将它写成一系列承诺调用。

function sleep(ms) { 
    var beginAnnounce = new Promise(...);
    var goSleep = new Promise (...);
    var endAnnounce = new Promise...);

    return beginAnnounce.then(goSleep).then(endAnnounce());

}

In the second snippet, you need to resolve begin immediately在第二个片段中,您需要立即解决begin

var begin = new Promise(resolve => {
  console.log("Sleep function called for " + ms + " ms\n")
  resolve()
})

The reason it works in the first snippet is because you never rely on begin to finish, you just have it there to log the start.它在第一个片段中工作的原因是因为你从不依赖begin到结束,你只是在那里记录开始。 But that's not the way you want to do it.但这不是您想要的方式。 There's no point having a Promise that resolves immediately (not for your use case anyway).有一个立即解决的 Promise 是没有意义的(无论如何不适用于您的用例)。 So you should rather do something like:所以你应该做这样的事情:

function sleep(ms) {
  console.log("Sleep function called for " + ms + " ms\n")

  return new Promise(resolve => {
    setTimeout(() => {
      console.log("Sleep done!")
      resolve()
    }, ms)
  })
}

If you want to compose two promises, you can return the second one in a callback passed to Promise.prototype.then of the first promise.如果你想组合两个承诺,你可以在传递给第一个承诺的Promise.prototype.then的回调中返回第二个。

Have a look at the following code:看看下面的代码:

 const sleep = ms => () => new Promise((resolve, reject) => window.setTimeout(resolve, ms)); Promise.resolve() .then(() => { console.log('A1');}) .then(sleep(2000)) .then(() => {console.log('A2');}); Promise.resolve() .then(() => {console.log('B1');}) .then(sleep(1000)) .then(() => {console.log('B2');});

The sleep function is a higher order function which returns another function that returns a promise. sleep函数是一个高阶函数,它返回另一个返回承诺的函数。 This promise is resolved in the call to Window.setTimeout parametrized by the ms passed to sleep .这个承诺在对Window.setTimeout的调用中得到解决,该调用由传递给sleepms参数化。

As you can see the executions are interleaved and you will see the log output for the statement console.log('B2') of the second promise before the output for console.log('A2');正如您所看到的,执行是交错的,您将在console.log('A2');的输出之前看到第二个承诺的语句console.log('B2')的日志输出console.log('A2'); of the first one.第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM