使用 promise 延迟 return 函数

Delay return from function using promise

我想要 运行 包含以下内容的函数: 如果条件得到解决 1) 添加 class 2) 睡眠 4 秒然后删除 class 3) 然后使用 return.

停止 运行ning 函数
    function sleep(time) {
    return new Promise(resolve => {
        setTimeout(resolve, time)
    })
  }
    function playGame() {
    if (counter === 3) {
        Promise.resolve().then(function () {
            message.classList.add('winner');
            sleep(2500).then(function () {
                message.classList.remove('winner');
            });
        });
        return;
      }
    ...
   }

如果我 运行 这段代码,当然会立即运行 returning。如何将 return 添加到承诺链。

这应该有效:

Promise.resolve()
.then(function () {
    message.classList.add('winner');
})
.then(sleep(2500))
.then(function() {
    message.classList.remove('winner');
});

这应该是不言自明的。如有需要,请随时提出更多问题。

EDIT : 糟糕,看来我回答得太快了。您永远不能在 javascript 中推迟 "return" 语句。在您的情况下,您的代码或我的代码立即执行,并立即调用封闭函数的 return ,然后执行返回到事件循环。 Then,调用promise的第一个then()等...

由于您无法推迟函数的 return,因此您使用回调,或者更好的是 Promises,来链接事件:

function playGame() {
    return Promise.resolve()  // note the return !
    .then(function () {
        message.classList.add('winner');
    })
    .then(sleep(2500))
    .then(function() {
        message.classList.remove('winner');
    });
}

...then

playGame()
.then(function() {
    // this code is called after playGame's Promise has been executed
});

// this code is called when playGame ends, ie immediately, and before any promises code

换句话说:一旦你开始拥有异步代码(通过回调或承诺),每一个进一步的代码也需要由承诺驱动。