Tuesday, 27 June 2017

javascript - Angular2: Returning Promise

you can create your own promise like this:


var myPromiseFunction = function(iserr){
var deferred = $q.defer();
var myreturnvalue = 'somevalue';
if(iserr === true){
deferred.reject('some error');
}else{
deferred.resolve(myreturnvalue);
}
return deferred.promise;
}

And call it like this:


var throwerror = false;
//or var throwerror = true; if you want to create an error
myPromiseFunction(throwerror).then(function(res){
console.log(res);
}).catch(function(err){
console.log(err);
})

This way you can create promises (they don't even have to be async but it would not have any purpose for non-async operations.

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...