for循环后的代码在node.js中运行之前执行

时间:2020-03-26 20:09:22

标签: node.js promise

在下面的代码中,我正在使用Promise.all()从API端点获取数据。结果被映射到URL,我必须遍历它们以处理结果。但是循环之后的代码在循环之前一直在执行。我该如何解决? 谢谢。 代码:

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});


        }
    });
};

0 个答案:

没有答案