Posts

Showing posts with the label Promise

Can You Resolve An Angularjs Promise Before You Return It?

Answer : Short answer: Yes, you can resolve an AngularJS promise before you return it, and it will behave as you'd expect. From JB Nizet's Plunkr but refactored to work within the context of what was originally asked (i.e. a function call to service) and actually on site. Inside the service... function getSomething(id) { // There will always be a promise so always declare it. var deferred = $q.defer(); if (Cache[id]) { // Resolve the deferred $q object before returning the promise deferred.resolve(Cache[id]); return deferred.promise; } // else- not in cache $http.get('/someUrl', {id:id}).success(function(data){ // Store your data or what ever.... // Then resolve deferred.resolve(data); }).error(function(data, status, headers, config) { deferred.reject("Error: request returned status " + status); }); return deferred.promise; } Inside the ...

Angularjs $q.all

Answer : In javascript there are no block-level scopes only function-level scopes : Read this article about javaScript Scoping and Hoisting. See how I debugged your code: var deferred = $q.defer(); deferred.count = i; console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects // some code .success(function(data){ console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object deferred.resolve(data); }) When you write var deferred= $q.defer(); inside a for loop it's hoisted to the top of the function, it means that javascript declares this variable on the function scope outside of the for loop . With each loop, the last deferred is overriding the previous one, there is no block-level scope to save a reference to that object. When asynchronous callbacks (success / error) are invoked, they reference only the last deferred object and only it gets resolved, so $q.all is never resolved because it still waits for other deferred ob...

Angular / TypeScript - Call A Function After Another One Has Been Completed

Answer : So remove the setTimeout part. It will call resolve or reject and then pass the execution to the next then or catch handler. If you have some asynchronous call in the Promise, you need to call resolve/reject in the result of that call. What about not waiting 1500ms - the given time is actually the lowest time after which the function may be called. Maybe after 2000ms This is related to the main thread in which JS code works. If main thread has no work to done, then the results of the asynchronous calls are going to be executed. function f1() { return new Promise((resolve, reject) => { console.log('f1'); resolve(); }); } function f2() { console.log('f2'); } f1().then(res => f2()); If f1 is synchronous , there is nothing special to do: global() { f1(); f2(); } If f1 is asynchronous and return an Observable , use Rxjs operator , like concatMap: global() { f1().concatMap(() =>...

Async/await In Angular `ngOnInit`

Answer : It is no different than what you had before. ngOnInit will return a Promise and the caller will ignore that promise. This means that the caller will not wait for everything in your method to finish before it proceeds. In this specific case it means the view will finish being configured and the view may be launched before this.data is set. That is the same situation you had before. The caller would not wait for your subscriptions to finish and would possibly launch the app before this.data had been populated. If your view is relying on data then you likely have some kind of ngIf setup to prevent you from accessing it. I personally don't see it as awkward or a bad practice as long as you're aware of the implications. However, the ngIf can be tedious (they would be needed in either way). I have personally moved to using route resolvers where it makes sense so I can avoid this situation. The data is loaded before the route finishes navigating and I can...

Catching Errors In JavaScript Promises With A First Level Try ... Catch

Answer : You cannot use try-catch statements to handle exceptions thrown asynchronously, as the function has "returned" before any exception is thrown. You should instead use the promise.then and promise.catch methods, which represent the asynchronous equivalent of the try-catch statement. (Or use the async/await syntax noted in @Edo's answer.) What you need to do is to return the promise, then chain another .catch to it: function promise() { var promise = new Promise(function(resolve, reject) { throw('Oh no!'); }); return promise.catch(function(error) { throw(error); }); } promise().catch(function(error) { console.log('Caught!', error); }); Promises are chainable, so if a promise rethrows an error, it will be delegated down to the next .catch . By the way, you don't need to use parentheses around throw statements ( throw a is the same as throw(a) ). With the new async/await syntax you can achieve this...