user3074989
user3074989

Reputation: 111

Need some help making a promise function to use a .then

I am currently working on a "pre made" project, so I am trying not to change too much of it.

I have a promise function that calls an API and get an array of objects, when creating a map, but it takes too much and it is called everytime a map needs to be created:

self.getStoreMapById = function(mapsId) {
      var deferred = $q.defer();
      $http.get("/api/stores/"+mapsId+'/map')
      .then(function (response) {
        deferred.resolve(response);
      });
      return deferred.promise;
    }

(This is how it gets called:

Stores.getStoreMapById(CONFIG.map.id).then(function(mapResp){

So, to avoid waiting a lot of time, I am calling that function once, when the app begins and save the data in 3 different global variables

if(maplevel1 == undefined ){
            Stores.getStoreMapById(24).then(function(mapResp){
                maplevel1 = mapResp.data;
            });
        } //same for maplevel2 and 3

now, what I want to do is, instead of using this Stores.getStoreMapById to call it everytime I need to create a map, I want to have a function that checks the id and assing the data to another var:

if(mapsId == "24"){
            data = maplevel1;
        }
        if(mapsId == "23"){
            data = maplevel2;
        }
        if(mapsId == "21"){
            data = maplevel3;
        }

Is there a way to write that in a promise function so I can call:

assingMap(CONFIG.map.id).then(function(mapResp){

and keep the rest of the code unchanged?

Thanks!

Upvotes: 3

Views: 41

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074178

Yes, you return a resolved promise containing the map:

function assignMap(mapsId) {
    var map = /*...find the map in your variables...*/;
    return $q.resolve(map); // With ES2015's promises, this would be
                            // `return Promise.resolve(map);`
}

That uses $q.resolve to get a pre-resolved promise. (This is an alias for $q.when; it's there to maintain naming consistency with ES2015's Promise.resolve(value).)

A key aspect of promises is that the then callback is always called asynchronously, even if the promise is already resolved, so code using this won't suddenly get different timing than it used to (other than that the delays will be shorter).


Re the "find the map in your variables" part, while you could use the long if/else if sequence you listed, you probably instead want to use a map of maps:

var maps = Object.create(null);
maps[24] = maplevel1; // You can do away with the maplevel1, maplevel2,
maps[23] = maplevel2; // and maplevel3 variables entirely if you create
maps[21] = maplevel3; // the map in the code getting these up front

Then:

var map = maps[mapsId];

Upvotes: 3

Related Questions