$q promise with Underscore _each

后端 未结 3 1387
忘了有多久
忘了有多久 2020-12-07 02:30

So I have a method in a angularjs server that is calling a method that returns a promise for each method in a array. I am using underscore _each to loop through the array. I

3条回答
  •  情歌与酒
    2020-12-07 03:24

    after I read the question and the according answer, I got on the right track. Thanks so far! But for the final working soltion I spent another hour to get all use cases working. That's why I would like to share a code example which contains chained promises including an array of promises to wait for resolution.

    Use case background is a server-side (nodeJs) file import after upload. I used promises in order to return an appropriate http status and result.

    readFile: function (fileName) {
        if (fileName) {
            var deferred = Q.defer();
            var self = this;
            converter({input: fileName}, function (error, userData) {
                if (error) {
                    deferred.reject(error);
                }
                self.storeUsers(error, userData)
                    .then(function (success) {
                        if (success) {
                            deferred.resolve(success)
                        }
                    })
                    .fail(function (error) {                       
                        deferred.reject(error)                      
                    });
            });
            return deferred.promise;
        }
    },
    
    storeUsers: function (error, data) {
        return Q.all(_.map(data, function (users, emailAddress) {
            var deferred = Q.defer();
            userRepository.findUserByEmail(emailAddress, function (user) {
                //...
                user.save(function (error) {
                    if (error) {
                        deferred.reject(error);
                    } else {
                        deferred.resolve(emailAddress);
                    }
                });
    
            });
            return deferred.promise;
        }));
    }
    

    Hope that helps too!

    Cheers Ben

提交回复
热议问题