承诺更改背景颜色出错

Promise to change background color gone wrong

我正在学习JS中的promises,无意中尝试了一些东西,但最终还是产生了疑问。我已经在 //comments 中提到了我对代码的期望。网页上的实际变化是 - 1 秒后 backgroundColor 变红,但之后颜色没有变化!!

    const colorChange = (newColor) => {
        return new Promise((resolve, reject) => {
            resolve(newColor); // returns resolved promise without any delay
        })
    }
    
    colorChange("red")
        .then((newColor) => {
            setTimeout(() => {
                console.log('in 1st then ', newColor);
                document.body.style.backgroundColor = newColor;
                return colorChange("yellow"); // I think this will return a resolved promise after (1 sec from start)
            }, 1000);
        })
        .then((newColor) => { // I think after (1 sec from start) this will get executed
            setTimeout(() => {
                console.log('in 2nd then ', newColor); // I thought that this should be yellow, but it is undefined!! why?
                document.body.style.backgroundColor = newColor; // I think this will get executed after (2 sec from start)
            },1000);
        })

控制台

in 1st then  red
in 2nd then  undefined

谁能解释一下这段代码 运行?

PromisesetTimeout 是异步的,return 在它们的回调中执行某些操作不会影响外部函数的 return,因为它的执行已经完成。

如果你愿意,你可以这样尝试,基于计时器解决承诺。

const colorChange = (newColor, resolveAfter) => {
    return new Promise((resolve, reject) => {
      if (resolveAfter) {
          setTimeout(() => resolve(newColor), resolveAfter);
      } else {
        resolve(newColor); // returns resolved promise without any delay
      }
    })
}

colorChange("red")
.then((newColor) => {
      console.log('in 1st then ', newColor);
      document.body.style.backgroundColor = newColor;
       //this will return a resolved promise after (1 sec from start)
    return colorChange("yellow", 1000);
})
.then((newColor) => { // after 1 sec from start this will get executed
    document.body.style.backgroundColor = newColor;
})

new Promise(function(resolve, reject) {

  setTimeout(() => resolve("red"), 1000); // (*)

}).then(function(result) { // (**)


  console.log('in 1st then ', result);
  document.body.style.backgroundColor = result;
  result = "yellow"
  return result ;

}).then(function(result) { // (***)

    console.log('in 2second then ', result);
    document.body.style.backgroundColor = result;
    result= "blue"
    return result ;

}).then(function(result) {

    console.log('in 3th then ', result);
    document.body.style.backgroundColor = result;
    result= "red"
    return result ;

});