Код после того, как for l oop выполняется перед тем, как l oop запускается в node.js - PullRequest
0 голосов
/ 26 марта 2020

В приведенном ниже коде я извлекаю данные из конечной точки API с помощью Promise.all(). Результаты сопоставляются с URL-адресами, и мне нужно перебирать их, чтобы обработать результаты. Но код после l oop продолжает выполняться до l oop. Как я могу это исправить? Спасибо. Код:

con.collection("users").find(input).toArray((error,results) => {
        if(error){
            throw error;
        }
        if(!results.length){
            response.json({"msg":"user not found"});
        } else{

            //call google maps API to get address an make inverse index entry 

            //call gmaps API for each location

            //form urls
            urls = []
            locations.forEach(location => {
                lat = location.lat;
                long = location.long;
                urls.push( url+lat.toString()+","+long.toString()+"&key="+API_KEY)

            });
            console.log(urls);

            var locations_temp = []

            Promise.all(urls.map(url_ => 
                fetch(url_)
                    .then(checkStatus)
                    .then(parseJSON)
                    .catch(error => console.log("There was an error",error))
                ))
                .then(data => {
                    data.forEach((entry,index) => {
                        console.log(entry.results[0].formatted_address);
                        locations_temp.push(entry.results[0].formatted_address);
                    })
                });

            //this gets executed before the loop above. 
            console.log(locations_temp);
            console.log("here");
            console.log("locations:",locations_temp);
            //USER EXISTS, APPEND LOCATIONS 
            filter = {$push:{locations:{$each:locations_temp}}};
            con.collection("users").update(input,filter)
                .then(() => response.sendStatus(200))
                .catch((error) => {throw error});


        }
    });
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...