Create empty promise in angular?

JavascriptAngularjs

Javascript Problem Overview


I want to do something like this:

var promise = IAmAEmptyPromise;

if(condition){
    promise = ApiService.getRealPromise();
}

promise.then(function(){
    //do something
});

So I want to declare a promise, which can be resolved using then. However this promise may be overwritten by another promise, which returns content. Later I want to resolve the promise whether it has content or not. Is this possible? I tried with:

var promise = $q.defer().promise;

if(!$scope.user){
    promise = UserService.create(params);
}

promise.then(function(){
   //either user was created or the user already exists.
});

However this does not work when a user is present. Any ideas?

Javascript Solutions


Solution 1 - Javascript

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.
});

Solution 2 - Javascript

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.');
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUpCatView Question on Stackoverflow
Solution 1 - JavascriptAnders EkdahlView Answer on Stackoverflow
Solution 2 - JavascriptBen DavisView Answer on Stackoverflow