Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create empty promise in angular?

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?

like image 601
UpCat Avatar asked Mar 19 '14 12:03

UpCat


People also ask

How do I send an empty promise?

An "empty promise" is another way of saying "a lie" in english.. so having an instantly resolved promise is better, just from a language standpoint ;) Promise. resolve() worked for me! new Promise now requires a parameter, use Promise.

How do I return a blank promise in TypeScript?

To return an empty promise with JavaScript, we can use an async function or call Promise. resolve . to create 2 functions that returns empty promises. p1 is an async function, so it's a function that always returns a promise.

What is an empty promise?

Empty-promise definition (idiomatic) A promise that is either not going to be carried out, worthless or meaningless. noun.


1 Answers

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. }); 
like image 166
Anders Ekdahl Avatar answered Sep 19 '22 01:09

Anders Ekdahl