Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise.all(...).spread is not a function when running promises in parallel

Tags:

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

This is my code:

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?

like image 648
Filipe Ferminiano Avatar asked Mar 12 '17 16:03

Filipe Ferminiano


People also ask

Does Promise all work in parallel?

all executes them in parallel.

Do JavaScript promises run in parallel?

One of the great things about JavaScript promises is flexibility in how they are run. Unlike callbacks, which are always executed sequentially (one after another), you have options for how to run multiple promises. Promises provide you with several options for how you can run promises in parallel.

How many promises can run in parallel?

Assuming we have the processing power and that our promises can run in parallel, there is a hard limit of just over 2 million promises.

Does Promise all work sequentially?

all() method executed by taking promises as input in the single array and executing them sequentially.


1 Answers

I'll make my comment into an answer since it solved your issue.

.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:

Access array values directly

You can just use .then(results => {...}) and access the results as results[0] and results[1].

Include the Bluebird Promise library

You can include the Bluebird promise library so you have access to .spread().

var Promise = require('bluebird');

Use destructuring in the callback arguments

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});
});
like image 141
jfriend00 Avatar answered Sep 25 '22 13:09

jfriend00