Javascript 使用嵌套的then语句传递值
我有一个函数,其格式如下:Javascript 使用嵌套的then语句传递值,javascript,es6-promise,Javascript,Es6 Promise,我有一个函数,其格式如下: this.callPromiseFunction1(params) .then(results1 => { if (results1.length > 2) { this.callPromiseFunction2(params) .then(results2 => { return results2.stuff; }).catch(reject); } else
this.callPromiseFunction1(params)
.then(results1 => {
if (results1.length > 2) {
this.callPromiseFunction2(params)
.then(results2 => {
return results2.stuff;
}).catch(reject);
} else {
return results1.stuff;
}
})
.then(results3 => {
this.callPromiseFunction3(someotherparams)
//do stuff
}).catch(reject)
我的问题是,如果我在第一个then()
语句中输入条件并调用承诺,就会出现计时问题,结果3未定义。如果我输入第一条then()
语句的else
语句,则定义结果3
我如何解决这个时间问题并允许嵌套的
then()
语句和承诺,而不完全重写我的承诺并强制它们一起工作?在继续下一个then()
)之前,是否有办法强制在then语句中完成承诺?您可以通过返回承诺来解决该问题。如果您注意到,在代码的If语句执行的情况下,您不会返回任何内容。返回承诺将导致它在承诺链的下一个链接之前插入。另外,您不需要在上面添加catch
,因为最后一个catch
会处理这个问题。另外,提前返程也是个好主意。这就是您的代码的外观:
this.callPromiseFunction1(params)
.then(results1 => {
if(results1.length <= 2) return results1.stuff;
return this.callPromiseFunction2(params)
.then(results2 => results2.stuff);
})
.then(results3 => {
this.callPromiseFunction3(someotherparams)
//do stuff
})
.catch(reject);
this.callPromiseFunction1(参数)
。然后(结果1=>{
if(results1.length results2.stuff);
})
。然后(结果3=>{
this.callPromiseFunction3(其他参数)
//做事
})
.捕获(拒绝);
您只需要在if语句中返回承诺。您的意思是调用return callPromiseFunction2(params)
?我是否仍会在该范围内返回并保留返回结果2.stuff,或者是否需要重新格式化?似乎只需添加返回
就可以了,但我不想因为奇怪的异步而错过任何边缘案例behavior@AdamS,是的,这是您添加的正确的返回值。你仍然需要说returnresults2.stuff代码>也是。谢谢@Vic!我现在觉得很傻,因为我在这个问题上坚持了这么久。感谢您的帮助让我注意,您不能从外部函数从内部函数返回箭头函数。您刚刚从arrow函数返回。