简体   繁体   中英

how to make multiple api calls node.js promises

I'm new to promises and async programming in javascript, and I'm trying to make multiple API calls to google maps places API in node.js then send data to the client once all the data is received. However, I'm getting some kind of a syntax error saying missing ) after argument list. Sorry if I'm asking a stupid question, I just can't seem to figure the issue out. Thanks for the help!

const fetch = require('node-fetch');

module.exports = (app) => {

    app.post('/search-champ', (req, res) => {


        console.log(req);
        let lat = req.body.param.lat; //before: req.query.lat it's wrong

        let long = req.body.param.long;
        console.log(lat);

        const apiId = 'AIzaSyAeEPop5mofzDJhytOEMtxXaGWFqGB4Q3M';
        const urls = [

            'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + lat + ',' + long + '&rankby=distance&type=department_store&key=AIzaSyAeEPop5mofzDJhytOEMtxXaGWFqGB4Q3M',

            'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + lat + ',' + long + '&rankby=distance&type=food&key=AIzaSyAeEPop5mofzDJhytOEMtxXaGWFqGB4Q3M'
        ];


        Promise.all(urls.map(url =>


            fetch(url)
            .then(checkStatus)


            .then(data => {

                console.log(data)
                res.send({
                    data

                });
            })

        }).catch(err => {
            res.redirect('/error');
        });

        function checkStatus(response) {
            if (response.ok) {
                return Promise.resolve(response);
            } else {
                return Promise.reject(new Error(response.statusText));
            }
        }




    })
}

The res.send({ data }); is called for every url in the array, this is probably not what you want, to wait for all api calls to complete, place the res.send() in the then() of the Promise.all()

Promise.all(urls.map(url =>
  fetch(url)
  .then(checkStatus)
).then(data => {
  console.log(data)
  res.send({ data });
}).catch(...)

Fetch in javascript return an response promise object you have to call the json method on it. Change your checkStatus method to this.

function checkStatus(response) {
            if (response.ok) {
                return Promise.resolve(response.json());
            } else {
                return Promise.reject(new Error(response.statusText));
            }
        }

Working solution:

const fetch = require('node-fetch');
module.exports = (app) => {
    app.post('/search-champ', (req, res) => {
        let lat = req.body.param.lat; //before: req.query.lat it's wrong
        let long = req.body.param.long;
        const apiId = 'AIzaSyAeEPop5mofzDJhytOEMtxXaGWFqGB4Q3M';
        const urls = [
            'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + lat + ',' + long + '&rankby=distance&type=department_store&key=AIzaSyAeEPop5mofzDJhytOEMtxXaGWFqGB4Q3M',
            'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + lat + ',' + long + '&rankby=distance&type=food&key=AIzaSyAeEPop5mofzDJhytOEMtxXaGWFqGB4Q3M'
        ];
        var apiData = urls.map( (url) => {
            return fetch(url).then(checkStatus);
        });
        Promise.all(apiData)
            .then( (data) => {
            res.send({
                data: data
            });
        });

        function checkStatus(response) {
            if (response.ok) {
                return Promise.resolve(response);
            } else {
                return Promise.reject(new Error(response.statusText));
            }
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM