简体   繁体   中英

Angularjs load resources on after the other using promise

Inside a service, I would like to load a resource using $http. Once loaded resource, I want to store it in a variable. Then, I need to load a child resource and store it too. I know that the promise is designed for this kind of work, but there seems to be so much how to use it I get a little confusion. Here is my code:

var project = {};
var todo = {};

function init(){
        var idProject = 21;
        var idTodo = 6;            

        // If idProject is specified
        if ( idProject != null ) {

            // First, load project data
            var promise = WorkspaceManager.getProject($rootScope.workspace, idProject);

            // Then save project data
            promise.then(function(response){
                project = response.data;                    
                return project;
            });

            if ( idTodo != null ) {
                //  Then load todo data
                promise.then(function(project){   
                    return ProjectManager.getTodo(project, idTodo);
                });

                // Then save todo data
                promise.then(function(response){
                    todo = response.data;                    
                    return todo;
                });
            }       
        }

        console.log(project); // returns {}
    }

init()

Thanks in advance !

The way you doing, you're creating "brothers" promise derived from the first promise. All the promises are going to be resolved as soon as WorkspaceManager.getProject promise has been resolved. What I believe you want is to chain them all, in way that when first promise gets resolved, yo asks for Todo data, when you got it, you asks to save it. If this is the case, you shall grab the derived promise from each promise.

// Then save project data
promise = promise.then(function(response){
  project = response.data;
  return project;
});

//  Then load todo data
promise = promise.then(function(project){   
  return ProjectManager.getTodo(project, idTodo);
});

// Then save todo data
promise.then(function(response){
  todo = response.data;                    
  return todo;
});

Trying to illustrate a bit more, the first approach is like:

var mainPromise = ...;
mainPromise.then(function loadTodo(mainPromiseReturn){});
mainPromise.then(function saveTodo(mainPromiseReturn){});

The loadTodo and saveTodo are pararell, they're not chained to each other. They both receive the same data .

The approach I suggest is like:

var mainPromise = ...;
mainPromise
  .then(function loadTodo(mainPromiseReturn){})
  .then(function saveTodo(loadTodoReturn){});

If I understand correctly, this is trickier than it appears at first glance. You appear to need a function that chains two asynchronous processes and returns a promise of a composite value comprising data acquired by the first and the second processes.

At least two approaches are available :

  • Easy but inelegant : In each asynchronous process, accumulate the required values as properties of an outer object.
  • Elegant but awkward : From each asynchronous process, accumulate the required values as properties of an object, a promise of which is returned.

The code below adopts the first approach :

function init() {
    var idProject = 21;
    var idTodo = 6;
    var projectObj = {};//This object acts as a "bank" for asynchrounously acquired data.
    if ( idProject != null ) {
        return WorkspaceManager.getProject($rootScope.workspace, idProject).then(function(response) {
            projectObj.project = response.data;//put `response.data` in the bank as .project.
            if( idTodo != null ) {
                return ProjectManager.getTodo(response.data, idTodo);
            }
        }).then(function(toDo) {
            projectObj.toDo = toDo;//put `toDo` in the bank as .toDo .
            return projectObj;
        });
    }
}

init().then(function(projectObj) {
    console.log(projectObj.project);
    console.log(projectObj.toDo);
});

Or (still the first approach) with error handlers :

function init() {
    var idProject = 21;
    var idTodo = 6;
    var projectObj = {};//This object acts as a "bank" for asynchrounously acquired data.
    if ( idProject != null ) {
        return WorkspaceManager.getProject($rootScope.workspace, idProject).then(function(response) {
            projectObj.project = response.data;//put `response.data` in the bank as .project.
            if( idTodo != null ) {
                return ProjectManager.getTodo(response.data, idTodo);
            }
            else {
                $q.defer().reject('idTodo invalid');
            }
        }).then(function(toDo) {
            projectObj.toDo = toDo;//put `toDo` in the bank as .toDo .
            return projectObj;
        });
    }
    else {
        return $q.defer().reject('idProject invalid');
    }
}

init().then(function(projectObj) {
    console.log(projectObj.project);
    console.log(projectObj.toDo);
}, function(errorMessage) {
    console.log(errorMessage);
});

untested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM