gpt4 book ai didi

javascript - Promise.all 不检查/存储所有 promise

转载 作者:行者123 更新时间:2023-11-28 17:28:03 27 4
gpt4 key购买 nike

我的 promise 有问题。所有的 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;

注释在代码中,但长话短说 - Promise.All 不会检查/存储所有 Promise。

更多关于SO“算法”的文本...以及更多...以及更多...以及更多...

最佳答案

Promise.all(promiseArray) 运行时,promiseArray 仅由前三个 Promise 组成 - 第四个来自 request直到请求完成后才会添加到 promiseArray 中,此时 Promise.all 已经解析。您必须为请求显式构造一个Promise,以便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');
});
}));

关于javascript - Promise.all 不检查/存储所有 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51127959/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com