Promise.all(...).spread 不是并行运行承诺时的函数 [英] Promise.all(...).spread is not a function when running promises in parallel

查看:96
本文介绍了Promise.all(...).spread 不是并行运行承诺时的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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 承诺库中可用.您包含的代码没有显示.三种可能的解决方案:

.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});
});

这篇关于Promise.all(...).spread 不是并行运行承诺时的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆