How to chain .then functions and callback success function in Angular.js

一曲冷凌霜 提交于 2019-11-29 13:04:24
Roamer-1888

Your { responseStatus: x } object exists solely for the purpose of flow control, which can be provided naturally by the success path and error path of a promise returned by fn();

Also, with promises, there's no need to pass a callback to fn() - indeed it is considered bad practice to do so.

So first,

  • purge callback all through
  • return a promise from each low level function
  • simplify success chaining
  • purge unnecessary error handlers
function fn() {
    return fn1().then(call1);
}
function call1() {
    return fn2().then(call2);
}
function call2() {
    return fn3().then(lastfunction);
}
function fn1() {
    //some code that returns a promise
}
function fn2() {
    //some code that returns a promise
}
function fn3() {
    //some code that returns a promise
}

Then, call as follows :

fn().then(function(response) {
    // success callback (your "200" condition)
    // show output;
}).catch(function(error) {
    // error callback (your "500" condition)
    // show error;
});

The response var will be whatever lastfunction() delivered. You have an issue if you want response to be some aggregation of what is delivered by fn1(), fn2(), fn3() that is not already delivered by lastfunction(). That issue is comprehensively addressed here.

The error var will be the first Error to occur in the course of executing fn(), with no loss of information; error.message and error.status (if it exists) can be read/displayed.

You need to return the promises you create in order to chain them properly. Keep in mind when you use .then() you aren't modifying a promise, you're constructing a new one in the chain.

Your code with promises returned (formatting mine):

function fn(callback) {
  return fn1()
    .then(function(response) {
      return call1(response);
    }, function(error) {
      return $q.reject({
      responseStatus: error.status
    });

    })
    // Return response
    .then(function(response) {
      callback({
        responseStatus: 200
      });
    }, function(error) {
      callback({
        responseStatus: 500
      });
    });
}

function call1(response) {
  return fn2()
    .then(function(response) {
        return call2(response);
      }, function(error) {
        return $q.reject({
        responseStatus: error.status
      });
    });
}


function call2(response) {
  return fn3()
    .then(function(response) {
        return lastfunction();
      //here i need to callback the success  response status
      }, function(error) {
        return $q.reject({
        responseStatus: error.status
      });
    });
}


function fn1(){
 //some code 
 }
function fn2(){
//some code 
}
function fn3(){
//some code 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!