Promise chain does not resolve; what is the correct way to fix?

Viewed 55

I am using rollup to build a web bundle for my page. I have one promise chain that is working fine, but another that is attempting to load a map that is not executing.

I've put breakpoints in, and I can see the break at the last line p().then((m)=>console.log) and Q.spread(...), but the other promised methods don't execute.

How am I failing to force the promise to resolve?

Here's my code:

'use strict';

import Q from 'q';
import GoogleMapsApiLoader from 'google-maps-api-loader';

var getPositionIP = function() {
    return new Q( (res,rej) => {
        let oReq = new XMLHttpRequest();
        oReq.onload = function (e) {
            let loc = { coords: e };
            res(loc);
        }
        oReq.open("GET","https://json.geoiplookup.io/");
        oReq.responseType = "json";
        oreq.send();
    });
};

var getPositionGPS = function(options) {
    return new Q( function(resolve, reject) {
        if( navigator.geolocation ) {
            navigator.geolocation.getCurrentPosition(resolve,reject,options);
        } else {
            reject();
        }
    });
};

let mapEngine = GoogleMapsApiLoader({
    libraries: [],
    apiKey: '<<google maps key>>'
});

let positionEngine = function() {
    return getPositionGPS({})
        .catch(() => getPositionIP());
};

let p = function() { 
    return Q.spread(positionEngine, mapEngine).then((pos,map) => {
        var mapcontainer = document.getElementById("map");
        return new map.Map(mapcontainer, {
            center: {lat: pos.coords.latitude, lng: pos.coords.longitude},
            zoom: 8
        }); 
    });
};

p().then((m)=>console.log);
1 Answers

That's not how Q.spread would work. A promise still resolves only to a single value, spread is about affecting how the callback will get called. According to the docs, you'll have to write either

return Q.spread([positionEngine, mapEngine], (pos, map) => {

or

return Q.all([positionEngine, mapEngine]).spread((pos, map) => {

The modern approach is to use parameter destructuring syntax though:

return Q.all([positionEngine, mapEngine]).then(([pos, map]) => {

which will also work when you migrate to ES6 promises.

Related