Promise.all(...).spread 不是并行运行 Promise 时的函数
我正在尝试使用 sequelize 并行运行 2 个 Promise,然后在 .ejs 模板中呈现结果,但我收到此错误:
I'm trying to run 2 promises in paralel with sequelize, and then render the results in a .ejs template, but I'm receiving this error:
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
});
});
我该如何解决这个问题?
How can I solve thhis?
推荐答案
因为它解决了你的问题,所以我会把我的评论变成答案.
I'll make my comment into an answer since it solved your issue.
.spread()
不是标准的 promise 方法.它在 Bluebird Promise 库中可用.您包含的代码没有显示这一点.三种可能的解决方案:
.spread()
is not a standard promise method. It is available in the Bluebird promise library. Your code you included does not show that. Three possible solutions:
直接访问数组值
您可以只使用 .then(results => {...})
并以 results[0]
和 results[1 的形式访问结果]
.
You can just use .then(results => {...})
and access the results as results[0]
and results[1]
.
包括 Bluebird Promise 库
您可以包含 Bluebird 承诺库,以便您可以访问 .spread()
.
You can include the Bluebird promise library so you have access to .spread()
.
var Promise = require('bluebird');
在回调参数中使用解构
在最新版本的 nodejs 中,您还可以使用解构赋值来消除对 .spread()
的需求,如下所示:
In the latest versions of nodejs, you could also use destructuring assignment which kind of removes the need for .spread()
like this:
Promise.all([template,list]).then(function([templates,lists]) {
res.render('campaign/create.ejs', {templates, lists});
});
相关文章