javascript - promise 中的多重 promise

标签 javascript typescript asynchronous promise

我想创建 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/

相关文章:

typescript - 如何确保两个元素要么一起存在于一个对象中,要么根本不存在?

asynchronous - Rust 中单线程异步应用程序的高效同步原语

c# - 如何在不断检查进度的同时在 ASP.NET 4 中异步加载页面?

javascript - React JS .map 与 JSON 中的对象同时返回所有数据

javascript - 使用 lodash 基于不同的值求和属性

javascript - knockoutjs 主页面调用组件

javascript - sendmail 传输的回调从未在 mocha 的 after Hook 中调用

javascript - HtmlWebpackPlugin 删除模板 div

javascript - 如何格式化仅包含日和月的给定日期?

typescript - 如何使用 ts.transform 将附加语句注入(inject)函数