在Angularjs中链接多个承诺 [英] Chain multiple promises in Angularjs

查看:70
本文介绍了在Angularjs中链接多个承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构,需要简化它,

I have the following structure and need to simplify it,

与IndexedDB交互的可恢复服务1

Resuable service1 to interact with IndexedDB

function isDbExist (){
// do something , it return either reject or resolve
}

function createDB (){
// do something , it return either reject or resolve
}

function getData (){
    // do something , it return either reject or resolve
}

在另一个service2中,我正在注入此service1并使用这些函数

In another service2 I'm injecting this service1 and using the functions as such

function1 (){
service1.isDbExist.then(function(data){
   service1.createDB.then(function(data){
      service1.getData.then(function(data){
        referred.resolve(data);
      },function(error){
       deferred.reject(error)
      })
   },function(error){
    deferred.reject(error);
   })
},function(error){
   deferred.reject(error);
})
}

这里的问题是代码的可读性不好,不容易调试哪个拒绝功能是哪个承诺。这是他们这样做的好方法吗?我已经阅读了关于$ q.all的信息,但是这并不适用于这种情况。

The problem here is the readability of the code is not good, its not easy to debug as which reject function is for which promise. Is their some good way of doing this ? I have read about $q.all but don't this its applicable in this situation.

推荐答案

确切地说,承诺的美丽是你可以链接它们而不是像回调那样嵌套它们。你可以在处理上一个时返回另一个承诺,如下所示:

Exactly, the beauty of promises is that you can chain them as opposed to nesting them like callbacks. You can return another promise when dealing with the previous like so:

isDbExists().then(function(db) {
  // do something
  return createDb();
}).then(function(db) {
  // do something with with the resolved db..
  return getData();
}).then(function(data) {
  // Do something with data
}).catch(function(error) {
  // Uh oh, something went wrong. Deal with error
});

最后,您处理可能发生的错误。

Finally, you deal with the error that may have occurred.

这篇关于在Angularjs中链接多个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆