Promise.all不会检查/存储所有承诺

时间:2018-07-02 00:31:09

标签: javascript es6-promise

我对诺言有问题。所有人都没有兑现所有诺言来解决...

简短示例:

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;

注释在代码中,但是长话短说-承诺。全部不检查/存储所有承诺。

SO'algorithm'的更多文本...更多...更多...更多...

1 个答案:

答案 0 :(得分:3)

Promise.all(promiseArray)运行时,promiseArray仅由前三个承诺组成-request中的第四个承诺直到请求后才添加到promiseArray中经过Promise.all的解析时间。您必须为Promise显式构造一个request,以便promiseArray在调用Promises之前具有所有必需的Promise.all

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