如何在数组上使用.then()?`

时间:2018-01-05 16:22:04

标签: javascript arrays promise

我在Express / Sequelize应用程序中做了很多基于承诺的操作。为了控制数据流,我希望尽可能地遵循promise模型。

以下是我正在做的事情的片段:

 AreaList.forEach( area => {
      distances.push({
        target: tgt,
        source: area,
        distance: areaController.calcDist(tgt, area),
        country: areaController.determineCountry(area)
      }).then(() => { //this is where I would like to have the .then() function, but get the error.
      distances.sort((a1, a2) =>{
        return a1.distance - a2.distance;
      }).filter(area => area.country === country)
      .forEach(area => {
       Insider.findAll({
        where: {
         areaCode: area.source,
         country: area.country,
         language: language,
         gender: gender
        }
      }).then( insider => {
        returnUsers.push(insiders);
      }).then(_ => {
        returnUsers = returnUsers.splice(0,10);
        res.status(200).send(returnUsers);
      });
    });
  });
});

如何为数组提供.then()或模拟.then()

2 个答案:

答案 0 :(得分:2)

您遇到的问题是将同步代码与异步代码混合在一起。在上面的代码片段中,您有各种同步代码。 AreaList.forEachdistances.pushdistances.sort都是同步操作。

我试图做的是处理一些代码,同时将其推入数组,这可能是也可能不是异步的(areaController.calcDist(tgt, area))。

我会重写这样的事情,假设areaController.calcDist(tgt, area)是一个同步操作:

let distances = AreaList.map(area => {
  return {
    target: tgt,
    source: area,
    distance: areaController.calcDist(tgt, area),
    country: areaController.determineCountry(area)
  };
})
.sort((a1, a2) =>{
    return a1.distance - a2.distance;
})
.filter(area => area.country === country);

let findUsers = distances.map(area => {
   return Insider.findAll({
    where: {
     areaCode: area.source,
     country: area.country,
     language: language,
     gender: gender
    }
   });
  });

Promise.all(findUsers).then(users => {
  let returnUsers = users.splice(0, 10);
  res.status(200).send(returnUsers);
})
.catch(err => {
  //handle errors
});

答案 1 :(得分:0)

then()是javascript promises resolve提供的函数。如果你想在浏览AreaList中的每个项目时做一系列的事情,你应该这样做:

pushDistances(distance) {
    return new Promise((resolve) => {
        distance.push(distance);
        resolve();
    });

使用resolve()函数,您可以直接解析()它,也可以附加您想要解决的内容:例如您刚刚按下的距离或更新的距离数组与新推的距离

resolve(distances) or resolve(distance);

然后在你的.then()中,根据你所解决的内容得到距离或距离。像这样:

pushDistances().then((distance or distances) => {
  within this function you have access to distance or distances: based on what you resolved with. 
});

然后你可以链接一堆返回promises的函数

pushDistances().then(() => anotherFunctionThatReturnsPromise()).then(() => {})

这是对promises如何运作的一般概述。你应该多看看 Javascript Promises了解如何将承诺联系起来。

相关问题