Search code examples
javascriptes6-promise

Promise.all does not check for/store all promises


I have problem with promise.All not catching all the promises to resolve...

short example:

const express = require('express');
const app = express();
const router = express.Router();
const request = require('request');

router.get('/', function(req, res)
{
    var promiseArray = [];

    function promiseResolve (data) {
        return new Promise (function (resolve) {
            resolve(data);
        });
    }

    var data1 = 1;

    promiseArray.push(promiseResolve(data1));

    var data2 = 2;

    promiseArray.push(promiseResolve(data2));

    var data3 = 3;

    promiseArray.push(promiseResolve(data3));

    console.log(promiseArray);

    **// all is fine**

    **// but when we add promise in some asynchronous operation like... request for example:**

    var test = request('https://www.google.com', function (err, res, content) {
        if (res.statusCode == 200)
        {
            promiseArray.push(promiseResolve(content));
            console.log(content);
        }
    });

    Promise.all(promiseArray).then(function(data) {
        console.log(data);
    });

    **// it does not store promise in a array... I thought that at first promise.All always 'check' if all promises are stored, then execute those by resolve, reject...**

  res.render('index');
});
module.exports = router;

comment are in code, but long story short - promise.All does not check for/store all promises.

Some more text for SO 'algorithm'... and more... and more... and more...


Solution

  • At the time Promise.all(promiseArray) runs, promiseArray is only composed of the first three Promises - the fourth one from request does not get added to promiseArray until after the request goes through, by which time the Promise.all has already resolved. You'll have to explicitly construct a Promise for the request so that promiseArray has all necessary Promises before Promise.all is called:

    promiseArray.push(new Promise((resolve, reject) => {
      request('https://www.google.com', function (err, res, content) {
        if (res.statusCode == 200) resolve(content);
        else reject('bad statusCode');
      });
    }));