Node.js承诺链不同步运行

时间:2018-01-29 15:56:05

标签: node.js

也许我(再次)误解了承诺,但我的承诺链并没有等到先前的承诺解决,然后再进入下一个承诺。

这是我的代码:

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

所以我希望在console.log("HERE ---> " + locationString);输出的最后一件事,但它在其他任何事情之前得到输出..为什么promise链中的最后一个函数不等待其他承诺解决?

1 个答案:

答案 0 :(得分:2)

试试这个:

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

我不确定我是否正确复制了所有内容,代码可以更好地编写(例如使用reduce代替for-loop),但我希望它会向您展示主要想法。