为什么这个递归捕获有时会为 .then 参数未定义?

Why this recursive catch is sometimes getting undefined for the .then parameter?

我是调试异步代码的新手,我迷失在调试器流程中。你能看出为什么 .then(greet) 中的 greet 参数有时未定义吗?

var tomsGreet = "Hello"

var thinkSomething = (idea) => {
  console.log("I'm thinking")
  return new Promise((fulfill, reject)=>{
    if(Math.round(Math.random() * 1))
      {
        fulfill("Hello Tom, how is your " + idea)
      }
    else{
      reject("Error found")
    }
    fulfill("Hello Tom, how is your " + idea)
  })
}

var respondToTom = (response) => {
    return this.thinkSomething("dog")
        .catch((error) => {
            console.warn(`Error in thinking`)
            if (error === 'Error found') {
                console.log(`Retrying thinking`)
                return this.respondToTom(this.tomsGreet)
            }
            else { throw error; }
        })
        .then((greet) => {
            if (greet == undefined){
              console.error("Ups undefined")
            }
            console.log(greet)
        });
}

this.respondToTom(tomsGreet);

改为将 .catch 放在 .then

之后
var respondToTom = (response) => {
    return thinkSomething("dog")
    .then((greet) => {
        if (greet == undefined){
            console.error("Ups undefined")
        }
        console.log(greet)
    })
    .catch((error) => {
        console.warn(`Error in thinking`)
        if (error === 'Error found') {
            console.log(`Retrying thinking`)
            return respondToTom(tomsGreet)
        } else {
            throw error;
        }
    })
}

当您从 .catch() 处理程序递归调用 responseToTom() 时,您依赖于 responseToTom() 将 return 解析为值的承诺这一事实。但是,在这段代码中:

    .then((greet) => {
        if (greet == undefined){
          console.error("Ups undefined")
        }
        console.log(greet)
    });

您没有 return 任何值,因此它将始终解析为 undefined 值。您可能想将 return greet 添加到 .then() 处理程序。