简体   繁体   English

Node.js承诺链不会同步运行

[英]Node.js promise chain not running synchronously

Maybe I'm misunderstanding promises (again) but my promise chain isn't waiting for the previous promise to resolve before moving onto the next. 也许我(再次)误解了诺言,但是我的诺言链并没有等待前一个诺言得以解决,然后才转到下一个诺言。

Here is my code: 这是我的代码:

function getLocations(){
  return new Promise((resolve, reject) => {
    request('https://api.sportradar.us/ncaamb/trial/v4/en/polls/ap/2017/rankings.json?api_key=MY_KEY', function (error, response, body) {
      resolve(body);
    });
  })
}

function convertLocations(body){
  return new Promise((resolve, reject) => {
    for(var i=0; i<15; i++){
      myLocation = JSON.parse(body).rankings[i].market

      var geocodeParams = {
        "address": myLocation
      }

      gmAPI.geocode(geocodeParams, function(err, result){
        areaLat = result.results[0].geometry.location.lat.toFixed(2);
        areaLong = result.results[0].geometry.location.lng.toFixed(2);
        console.log(areaLat + "  " + areaLong);
        locationString += areaLat + "  " + areaLong + "|";
      });

      params["markers"].push({location: myLocation})
    }

    resolve(locationString);
  })
}


getLocations()
.then((body) => convertLocations(body))
.then((locationString) => {
  console.log("HERE ---> " + locationString);
})

So the last thing that i want to be output in the console.log("HERE ---> " + locationString); 所以我想在console.log("HERE ---> " + locationString);输出的最后一件事 but it gets output before anything else instead.. why is the last function in the promise chain not waiting for the other promises to resolve? 但是它先输出,然后输出。.为什么诺言链中的最后一个函数不等待其他诺言解析?

Try this: 尝试这个:

function getLocations() {
  return new Promise((resolve, reject) => {
    request('https://api.sportradar.us/ncaamb/trial/v4/en/polls/ap/2017/rankings.json?api_key=MY_KEY', function (error, response, body) {
      resolve(body);
    });
  })
}

function convertLocation(location) {
  return new Promise((resolve, reject) => {
    // do whatever you need to convert, i'm not sure if i was careful enough when I copy-paste you code

    var geocodeParams = {
      "address": myLocation
    }
    gmAPI.geocode(geocodeParams, function (err, result) {
      areaLat = result.results[0].geometry.location.lat.toFixed(2);
      areaLong = result.results[0].geometry.location.lng.toFixed(2);
      console.log(areaLat + "  " + areaLong);
      resolve(areaLat + "  " + areaLong + "|"); // <---- reosolve promise !!!
    });

  })
}

function convertLocations(body) {

  var promises = [];
  var data = JSON.parse(body);


  for (var i = 0; i < 15; i++) {
    promises.push(convertLocation(data.rankings[i].market));
  }

  return Promise.all(promises).then(arrayOfResulst => {
    return arrayOfResulst.join('')
  })
}


getLocations()
  .then((body) => convertLocations(body))
  .then((locationString) => {
    console.log("HERE ---> " + locationString);
  })

I'm not pretty sure I copied all correctly, and code could be written better (eg use reduce instead of for-loop), but i hope it will show you main idea. 我不太确定我是否正确复制了所有代码,并且代码可以编写得更好(例如,使用reduce而不是for循环),但是我希望它可以向您展示主要思想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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