我想创建 then
链,但我的 promise 在内部 promise 执行之前就得到了解决。我该如何解决这个问题?
这段代码工作正常,但我想让它成为线性 promise 链
functiontest(abc):Promise<any> {
return new Promise((resolve, reject) => {
this.nativeStorage.getItem('test')
.then(test => {
if(test == 1) {
this.function2(abc).then(tagId=>{
this.function3(tagId).then(data=>{
resolve(data)
});
});
}else {
this.function3(abc).then(data=>{
resolve(data)
});
}
},
error => {
this.function2(abc).then(tagId=>{
this.function3(tagId).then(data=>{
resolve(data)
});
});
}
)
}); }
function3
仅当调用 function2
时才使用 function2
的结果,否则直接调用 function3
最佳答案
您的代码对于其实际用途来说确实太复杂了。当您已经从 getItem
获取 Promise 时,无需使用 new Promise
并且您应该避免嵌套 Promise 处理程序,例如 .then(...then( ....然后()))
.
以下代码在功能上应与您的代码等效:
function test(abc): Promise<any> {
return this.nativeStorage.getItem('test')
.then(test => {
if (test == 1) {
return this.function2(abc);
}
return abc;
})
.catch(() => this.function2(abc))
.then(tagId => this.function3(tagId));
}
您可能还想研究async
/await
作为以更简单的方式实现异步功能的方法。
关于javascript - promise 中的多重 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48566794/