Return angular promise from a function that quickly promises a promise

I am writing an asynchronous javascript function that will be called by consumers to get certain data. Below is a simple implementation that I wrote at the beginning (removing errors and removing other things for clarity).

function getData(callback){ if (data is available as a JavaScript object){ callback(data); }else{ getAsyncData(function(data){ //some transformations on data callback(data); }); } } 

It is important to note that getData can quickly return data if the data is already available as a JavaScript object.

I want to replace this implementation with one that returns a promise object to the caller. This script shows an example implementation - http://fiddle.jshell.net/ZjUg3/44/

Question. Since getData can return quickly, can it be possible when getData resolves the promise before the caller has established a chain of handlers using the then method? Just to simulate this, in the fiddle, if I call and then the method inside the setTimeout function (with zero delay), the callback will not be called. If I call the then method outside the setTimeout function, callback is called. I am not sure if this is even a valid concern or a valid usecase. I am completely new to angularjs development and will be grateful for your views :)

+4
source share
2 answers

No, a significant and important part of the promise is that it does not matter when you attach the handler. Even if you create a promise now and eliminate it immediately, then continue to work for the next 50 years, and then attach a handler that it will still run.

All this assumes that in the implementation of promises with angular errors there is no case with an error / angle. If this does not work, this is a mistake.

If you ever need to know anything about how promises works, you can always refer to Promises / A + spec , which is angular adheers to. As a specification, this is one of the simplest and easiest to understand that I came across (although I should mention that I have long been involved in the specification).

+3
source

If you want getData() to return the promise of $q instead of using a callback, I would do the following refactoring using $q.when() and regular $q.resolve() :

 function getData() { if (data is available as a JavaScript object) { return $q.when(data); // resolves immediately } else { var q = $q.defer(); getAsyncData(function(data){ //some transformations on data q.resolve(data); }); return q.promise; } } 
+5
source

Source: https://habr.com/ru/post/1493378/


All Articles