我对诺言有问题。所有人都没有兑现所有诺言来解决...
简短示例:
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'的更多文本...更多...更多...更多...
答案 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');
});
}));