如何使for循环等待异步函数

时间:2018-03-16 21:26:02

标签: javascript node.js asynchronous

我正在向predicthq API提出请求



app.get("/test", (req, res) => {
  // [0] IS THE LONGITUDE 
  request.get("https://api.predicthq.com/v1/events/?q=Minnesota&limit=10", {
    headers
  }, (err, data) => {
    var results = JSON.parse(data.body).results;
    var serverRes = [];

    for (var i in results) {

      getGeo(results[i].location[1],   results[i].location[0]).then(v => {
        serverRes[i] = v;
      })
    } //end of for loop

    res.send(serverRes)

  }); // end of request call
}); //end of GET CALL

//ASYNC FUNCTIOON
function getGeo(lat, long) {
  return new Promise(resolve => {
    geocoder.reverse({
      lat: lat,
      lon: long
    }, function(err, res) {
      resolve(res)
    });
  });
}

$(document).ready(function() {
    $("button").on("click", () => {
        console.log("Button Clicked");
        $.get("/test",  function(data, status){
            console.log("data", data)
        });
    });//end of button clicked
}); 




获取活动列表。当我得到响应时,我想转换lat,将响应的长度转换为地址并将其放入数组变量中。当我从服务器得到响应时,它给出了一个空数组的列表,如何使for循环等到geocoder.reverse获取数据,然后转到另一个lat,long

2 个答案:

答案 0 :(得分:2)

使用lambdarole = { dev = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/myRole" test = ... prod = ... } 循环将这些promises放入数组中,然后使用for等待它们解析。

Promise.all

答案 1 :(得分:0)

你试过async await吗?看着它,我认为这对你有用。

$(document).ready(function(){

$("button").on("click", async () => {
    console.log("Button Clicked");
     await $.get("/test",  function(data, status){
        console.log("data", data)
    });
});//end of button clicked

});