Javascript 比较承诺链模式

Javascript 比较承诺链模式,javascript,promise,es6-promise,Javascript,Promise,Es6 Promise,我有三个承诺 比方说,第一个承诺(foo)的结果作为第二个承诺(bar)的输入,而bar的结果作为第三个承诺(baz)的输入 constfoo=(标志)=>newpromise((res,rej)=>{ 设置超时(()=>{ 标志?res(“foo已解决”):rej(“foo已拒绝”) }, 1000) }) 常数条=(标志)=>新承诺((res,rej)=>{ 设置超时(()=>{ 标志?res(“已解决的酒吧”):rej(“拒绝的酒吧”) }, 1000) }) constbaz=(fla

我有三个承诺

比方说,第一个承诺(foo)的结果作为第二个承诺(bar)的输入,而bar的结果作为第三个承诺(baz)的输入

constfoo=(标志)=>newpromise((res,rej)=>{
设置超时(()=>{
标志?res(“foo已解决”):rej(“foo已拒绝”)
}, 1000)
})
常数条=(标志)=>新承诺((res,rej)=>{
设置超时(()=>{
标志?res(“已解决的酒吧”):rej(“拒绝的酒吧”)
}, 1000)
})
constbaz=(flag)=>新承诺((res,rej)=>{
设置超时(()=>{
标志?res(“baz已解决”):rej(“baz已拒绝”)
}, 1000)
})
/*现在我可以使用以下方法之一使用这些*/
foo(1)。然后(fooVal=>{
console.log(fooVal);
返回条(fooVal)。然后(barVal=>{
console.log(barVal);
返回baz(barVal)。然后(bazVal=>{
控制台日志(bazVal);
}).catch(err=>{console.log(err,“-->err from untidy baz”);throw err;})
}).catch(err=>{console.log(err,“-->err from untidy baz或bar”);throw err;})
}).catch(err=>{console.log(err,“-->err from untidy baz或bar或foo”);throw err;})
foo(1).then(fooVal=>{console.log(fooVal);返回条(fooVal)})
.catch(err=>{console.log(err,“-->err from foo”);throw err;})
.then(barVal=>{console.log(barVal);return baz(barVal)})
.catch(err=>{console.log(err,“-->err from foo或bar”);throw err;})
.then(bazVal=>{console.log(bazVal)})

.catch(err=>{console.log(err,“-->err from baz或bar或baz”);throw err;})
如您所述,这两种形式在语义上存在差异;它们并不等同。因此,“更好”就是你需要做的事情。为了保持整洁,请将所有内容转换为
async
/
await
/
try
/
catch
而不是这个承诺地狱。是的,我知道async/await非常干净,除了语义上的差异外,错误处理方法也有显著差异。您是否尝试执行第二个代码段?错误处理是我所指的语义差异:)
try{x();try{y();}catch…}catch…
不同于
try{x();}catch。。。;试试{y();}catch…
,它们是不可互换的,你需要根据你所面临的环境选择每次需要使用哪一种,而不是盲目地将其视为标准的“更好”。