我有一个快速应用程序,我想在其中加载相关和单独的模型并将它们单独提供给 View 。我已正确加载相关的公交车、家庭和人员模型,但现在还想加载 volunteerTypes 并将其作为单独的对象提供给 View 。

exports.get = (request, response) => { 
  bus.findAll({include: [{model: family, include: [person]}]}) 
      .then(buses => buses.map(addCount)) 
      .then(volunteerTypes => volunteerType.findAll()) 
      .then((buses, volunteerTypes) => response.render('pages/register', {buses: buses, volunteerTypes: volunteerTypes})); 
}; 

我认为这应该很简单,但是我无法确定正确的语法。 sequelize docs包含许多使用预先加载来加载相关数据的示例,但我可以找到一个示例来说明如何加载单独的模型。 FWIW, Node 控制台的输出确实表明在 volunteerType 模型上运行了单独的查询。因此,这可能只是正确存储此查询结果以便将其传递到 View 的问题。

更新:addCount 只是向总线数组中的每个总线添加一个属性。我认为这与我的问题无关,但这是所要求的代码:

const atCampPeople = thisFamily => thisFamily.dataValues.people.filter(pers => pers.isAtCampPerson).length; 
const countPeople = (count, thisFamily) => count + atCampPeople(thisFamily); 
 
const addCount = thisBus => { 
  thisBus.dataValues.count = thisBus.dataValues.families.reduce(countPeople, 0); 
  return thisBus.dataValues; 
}; 

请您参考如下方法:

因此,根据我的观察,我认为您对 Promise 缺乏一些理解。

这部分代码:

bus.findAll({include: [{model: family, include: [person]}]}) 
      .then(buses => buses.map(addCount)) 

返回一个解析 busses 数组的 Promise

虽然这部分

volunteerType.findAll() 

解析一个Promise,它解析为volunteerType的整个集合。

当你这样做时:

.then(volunteerTypes => volunteerType.findAll()) 

你真正做的是busses => Busses .findAll(),因为之前的 promise 解析了busses数组。因此,这应该返回未定义结果或抛出错误。

我的建议是加载 volunteerType 模型并将其传递到可以解析两个 Promise 的函数中。

下面是更正后的代码(请注意,我使用 Promise.all 同时解决两个不同的 promise ,一个用于获取总线并改变它们,另一个用于获取志愿者:

exports.get = (request, response) => { 
    return Promise.all([ 
        // Grab and mutate busses 
        bus.findAll({ 
            include: [{ 
                model: family, include: [person] 
            }] 
        }). 
        then(buses => buses.map(addCount)), 
        // grab volunteerType 
        volunteerType.findAll() 
    ]). 
    // This now returns an Array with the resolution of each promise 
    then( ([busses, volunteerType]) =>   
        response.render('pages/register', { 
            buses,  
            volunteerTypes 
        }) 
    ) 
}; 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!