user3074989 user3074989 - 1 year ago 68
Javascript Question

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();
.then(function (response) {
return deferred.promise;

(This is how it gets called:


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 ){
maplevel1 =;
} //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:


and keep the rest of the code unchanged?


Answer Source

Yes, you return a resolved promise containing the map:

function assignMap(mapsId) {
    var map = /*...find the map in your variables...*/;
    var p = $q.defer();      // In ES2015 promises, these three lines
    p.resolve(map);          // would be replaced by simply:
    return p.promise;        // return `Promise.resolve(map);`

(I'm not immediately seeing an equivalent of ES2015's Promise.resolve(map); in the angular $q documentation or Kris Kowal's project page.)

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


var map = maps[mapsId];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download