0

I used a design pattern (module pattern) to make a function and then invoke a function inside of that which that returns a promise but its returning "undefined"

Why is that? Here is my code:

// spotcrime -----  finds crime loggings of any given area lat/lon + radius
const Crimes = (function () {

    let data;

    let InitCrimes = function (latitude, longitude, radius) {

        let location = {
            latitude: latitude,
            longitude: longitude
        }

        spotcrime.getCrimes(location, radius, (err, crimeData) => {
            if (err) console.log(err);
            data += crimeData;
        });

        return new Promise ((resolve,reject) => {
            if (data !== undefined || data !== null) {
                resolve(data);
            } else {
                reject(err);
            }
        });
    }

    return {
        el_monte: function (latitude, longitude, radius) {
            InitCrimes(latitude, longitude, radius)
                .then(function(crimeData) {
                console.log(crimeData);
            }).catch(function(error) { return error; });
        }
    }

}());
// 34.052901, -118.019821       // el monte
Crimes.el_monte(34.052901, -118.019821, 0.5);
Chris
  • 973
  • 1
  • 8
  • 20

1 Answers1

0

That's because you forgot the return keywords in el_monte, and because the scoping in your InitCrimes function is totally messed up (also you're not waiting for the asynchronous callback before calling resolve).

Your code should look like this:

const Crimes = (function () {
    function initCrimes(latitude, longitude, radius) {
        return new Promise((resolve,reject) => {
            spotcrime.getCrimes({latitude, longitude}, radius, (err, crimeData) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(crimeData);
                }
            });
        });
    }

    return {
        el_monte(latitude, longitude, radius) {
            return initCrimes(latitude, longitude, radius).then(data => {
                console.log(data);
                return data;
            });
        }
    }
}());

Crimes.el_monte(34.052901, -118.019821, 0.5).then(data => {
    // do something with the data;
}).catch(error => { 
   console.error(error);
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375