尽管在.then()语句中,为什么推送到不等待异步任务完成的数组?

时间:2017-04-19 22:58:19

标签: javascript asynchronous

原谅/请纠正任何误用词汇:我正在从CORS请求中检索数据,并循环结果,每次迭代将对象推送到数组。我能够看到数组在增长,但只要$.get()请求完成,我的数组似乎又是空的。

我的猜测是$.get()命令是异步运行的,第二个console.log()命令只是在get完成之前执行。但是,我已将console.log()放在.then()命令中,但仍然遇到同样的问题。任何人都知道这里发生了什么,以及如何解决它?

Bike = function(dateStolen, frameColors, frameModel, id, imageUrl, manufacturer, serial, location, title, year){
  this.dateStolen = dateStolen;
  this.frameColors = frameColors;
  this.frameModel = frameModel;
  this.id = id;
  this.imageUrl = imageUrl;
  this.manufacturer = manufacturer;
  this.serial = serial;
  this.location = location;
  this.title = title;
  this.year = year;
};

Bike.prototype.addStolenBikesToArray = function(allBikes){
  $.get("https://bikeindex.org:443/api/v3/search?page=1&per_page=25&location=IP&distance=10&stolenness=stolen")
  .then(function(response){
    response.bikes.forEach(function(bike){
      var currentBike = new Bike(bike.date_stolen, bike.frame_colors, bike.frame_model, bike.id, bike.thumb, bike.manufacturer_name, bike.serial, bike.stolen_location, bike.title, bike.year);
      allBikes.push(currentBike);
      // this displays an ever-growing array of bike objects
      console.log(allBikes);
    })
  })
  // this displays an empty array
  .then(console.log(allBikes));
};

Bike.prototype.setColor = function (userName){
  this.userName = userName;
};

exports.bikeModule = Bike;

然后是我的界面文件:

var Bike = require("./../js/stolenBikes.js").bikeModule;

var determineMostStolenManufacturer = function(bikeArray){
  var manufacturerArray = getArrayOfManufacturers(bikeArray);
  console.log(manufacturerArray);
};

var getArrayOfManufacturers = function(bikeArray){
  var manufacturerArray = [];
  bikeArray.forEach(function(bike){
    manufacturerArray.push(bike.manufacturer);
  });
  return manufacturerArray;
};

$(function(){
  var currentBike = new Bike();
  var allBikes = [];
  currentBike.addStolenBikesToArray(allBikes);
});

Link to my github repo if needed

0 个答案:

没有答案