Create empty promise in angular?
When using native es-6 promises, you can use Promise.resolve() to create an immediately resolved promise. This is useful when composing promises.
var p = Promise.resolve();
for (var i=0; i<something.length; i++) {
p = p.then(UserService.create(newUsers[i]));
}
p.catch(function(e) {
console.error('oops: ', e);
}).then(function() {
console.log('done.');
});
Like Bixi wrote, you could use $q.when()
which wraps a promise or a value into a promise. If what you pass to when()
is a promise, that will get returned, otherwise a new promise is created which is resolved directly with the value you passed in. Something like this:
var promise;
if(!$scope.user){
promise = UserService.create(params);
} else {
promise = $q.when($scope.user);
}
promise.then(function(user){
//either user was created or the user already exists.
});