返回数组

时间:2018-06-15 15:51:19

标签: javascript promise iterable

我正在尝试编写一个返回两个对象数组的函数,这是一个promise。原版是相当冗长的,所以我试着缩写它:

  function initCalc() {
    var [av, driving] = calcCarRoute(start, end, dt)

    var results = [];
    results.push(av);
    results.push(driving);
    return results;
  };

  function calcCarRoute(start, end, dt) {
    var temp = new Promise(function(resolve, reject) {
      var driving = {};
      var directionsService = new google.maps.DirectionsService();
      var request = {
        //some code;
      };
      directionsService.route(request, function(result, status) {
        if (status == 'OK') {
          //some code;
          resolve(driving);
        };
      });
    });
    return temp.then(function(value) {
      var driving = value;
      //some code;
      return driving;
    }).then(function(value2) {
      var AV = {};
      //some code;
      return Promise.all([AV, value2]);
    })
  };

然而,在执行时,我收到错误: calcCarRoute is not a function or its return value is not iterable。我或多或少地确定问题在于我希望返回值是一个数组,因为我返回一个对象的结构相同的函数运行正常。我还尝试在calCarRoute中仅返回[AV, value2]而不是Promise.all(),但这也不起作用。

编辑:为了接受一些合理的评论,我开发了一个玩具模型。下面代码的目标是将calcFood()的返回值保存在两个promise中,以便我可以将它们链接起来以便以后进一步操作。

initCalc();

function initCalc() {
  var [staple, meat] = calcFood().then(function([value1, value2]) {
    return [value1, value2];
  });
  var other = calcOther();

  Promise.all([staple, meat, other]).then(function([staple, meat, other]){
    for (i=0; i<4; i++){
      console.log(JSON.stringify(staple));
      console.log(JSON.stringify(meat));
      console.log(JSON.stringify(other));    
    }
  })
};

function calcFood() {
  var temp = new Promise(function(resolve, reject) {
    resolve({Lunch:'Rice', Dinner:'Pasta'});
  });
  return temp.then(function(value) {
    var meat = {};
    Object.assign(meat, value);
    meat.Lunch = 'Fish';
    meat.Lunch = 'Chicken';
    return [value, meat];
  })
};
function calcOther() {
  var temp = new Promise(function(resolve, reject) {
    resolve({Other:'None'});
  });
  return temp;
};

0 个答案:

没有答案
相关问题