Pascal
Pascal

Reputation: 11

Promise inside a Promise?

I have a first promise to retrieve the lat/long of 2 addresses. Then once this promise is resolved, I want to parse a file matching these lat/long. The code works fine and in the callback of readFile, I can handle the values correctly. But then I would like to wait until the promise is resolved: the process function, but the 'then' for it returns right away. How do I wait until all the data in the files are proceed and the promise is resolved?

const fs = require('fs');
const request = require('request');

const path = 'https://maps.googleapis.com/maps/api/geocode/json?address=<address>&key=<key>';
const addresses = ['Boulder, CO', 'Denver, CO'];

const getLatLong = function(address) {
    let url = path;
    url = url.replace('<address>', encodeURIComponent(address));
    url = url.replace('<key>', '-----');

    return new Promise((resolve, reject) => {
        var req = request(url, (err, resp, body) => {
            resolve(body);
        });
    });
}

async function getAll(addresses) {
    const p1 = await getLatLong(addresses[0]);
    const p2 = await getLatLong(addresses[1]);
    return [p1, p2];
}

const getActivities = function() {
    getAll(addresses).then(p => {
        return new Promise((resolve, reject) => {
            fs.readFile('all.json', 'utf8', (err, contents) => {
                let all = [];
                let activities = JSON.parse(contents);
                activities.forEach(activity => { all.push(activity); });
                resolve(all);
            });
        });
    });
}

async function process() {
    return await getActivities();
}

process().then(activities => {
    console.log(activities);
});

Upvotes: 0

Views: 3259

Answers (1)

unional
unional

Reputation: 15619

You are missing a return:

const getActivities = function() {
    return getAll(addresses).then(p => { // <--- here
        return new Promise((resolve, reject) => {
            fs.readFile('all.json', 'utf8', (err, contents) => {
                let all = [];
                let activities = JSON.parse(contents);
                activities.forEach(activity => { all.push(activity); });
                resolve(all);
            });
        });
    });
} 

Upvotes: 1

Related Questions