[英]Why this recursive catch is sometimes getting undefined for the .then parameter?
I'm new in debugging async code, and I get lost in the debugger flow.我是调试异步代码的新手,并且在调试器流程中迷失了方向。 Can you spot why the greet parameter in .then(greet) is sometimes undefined?
你能发现为什么 .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);
Change to put the .catch
after .then
切换到放
.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;
}
})
}
When you recursively call responseToTom()
from the .catch()
handler, you are relying on the fact that responseToTom()
will return a promise that resolves to a value.当您从
.catch()
处理程序递归调用responseToTom()
,您依赖于这样一个事实,即responseToTom()
将返回一个解析为值的承诺。 But, in this code:但是,在这段代码中:
.then((greet) => {
if (greet == undefined){
console.error("Ups undefined")
}
console.log(greet)
});
You aren't returning any value so that will always resolve to an undefined
value.您没有返回任何值,因此将始终解析为
undefined
值。 You probably want to add return greet
to that .then()
handler.您可能希望向该
.then()
处理程序添加return greet
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.