我尝试与sequelize 并行运行2 个promise,然后在.ejs 模板中渲染结果,但我收到此错误:
Promise.all(...).spread is not a function
这是我的代码:
var environment_hash = req.session.passport.user.environment_hash;
var Template = require('../models/index').Template;
var List = require('../models/index').List;
var values = {
where: { environment_hash: environment_hash,
is_deleted: 0
}
};
template = Template.findAll(values);
list = List.findAll(values);
Promise.all([template,list]).spread(function(templates,lists) {
res.render('campaign/create.ejs', {
templates: templates,
lists: lists
});
});
我该如何解决这个问题?
我会将我的评论作为答案,因为它解决了您的问题。
.spread()
不是标准的 Promise 方法。它可以在 Bluebird Promise 库中找到。您包含的代码没有显示这一点。三种可能的解决方案:
直接访问数组值
您可以仅使用
.then(results => {...})
并通过 results[0]
和 results[1]
访问结果。
包含 Bluebird Promise 库
您可以包含 Bluebird Promise 库,以便您可以访问
.spread()
。
var Promise = require('bluebird');
在回调参数中使用解构
在最新版本的nodejs中,您还可以使用参数解构,这样就不再需要
.spread()
,如下所示:
Promise.all([template,list]).then(function([templates,lists]) {
res.render('campaign/create.ejs', {templates, lists});
});
您可以在没有非标准
Bluebird
功能的情况下编写它,并保留更少的依赖项。
Promise.all([template,list])
.then(function([templates,lists]) {
};
Promise.all([
Promise.resolve(1),
Promise.resolve(2),
]).then(([one, two]) => console.log(one, two));
这是一个
Bluebird
Promise 功能,您可以通过 Sequelize.Promise
访问它,而无需安装 Bluebird
模块本身
Sequelize.Promise.all(promises).spread(...)
我需要安装 BlueBird。
npm install bluebird
然后:
var Promise = require("bluebird");