为什么我的 Promises 数组在调用 Promise.all() 之前运行? [英] Why is my array of Promises running before calling Promise.all()?
问题描述
我正在尝试创建一个 Promise 数组,然后使用 Promise.all() 解决它们.我正在使用 got,它返回一个承诺.
I am trying to create an array of Promises, then resolve them with Promise.all(). I am using got, which returns a promise.
我的代码有效,但我不完全理解如何.这是:
My code works, but I don't fully understand how. Here it is:
const got = require('got');
const url = 'myUrl';
const params = ['param1', 'param2', 'param3'];
let promiseArray = [];
for (param of params) {
promiseArray.push(got(url + param));
}
// Inspect the promises
for (promise of promiseArray) {
console.log(JSON.stringify(promise));
// Output: promise: {"_pending":true,"_canceled":false,"_promise":{}}
}
Promise.all(promiseArray).then((results) => {
// Operate on results - works just fine
}).catch((e) => {
// Error handling logic
});
让我失望的是,当我将 Promise 添加到数组中时,它们被标记为pending",这意味着它们已经开始.
What throws me off is that the Promises are marked as "pending" when I add them into the array, which means they have already started.
我认为它们应该在 promiseArray
中处于非活动状态,并且 Promise.all(promiseArray)
会启动它们并解决它们.
I would think that they should lie inactive in promiseArray
, and Promise.all(promiseArray)
would both start them and resolve them.
这是否意味着我要启动它们两次?
Does this mean I am starting them twice?
推荐答案
您不会启动它们两次.Promise 一创建就开始运行——或者只要 JS 引擎找到足够的资源来启动它们.您无法控制它们何时真正开始.
You're not starting them twice. Promises start running as soon as they're created - or as soon as the JS engine finds enough resources to start them. You have no control on when they actually start.
所有 Promise.all()
所做的就是等待它们全部解决(解决或拒绝).Promise.all()
不会干扰或影响 Promise 本身的执行顺序/时间.
All Promise.all()
does is wait for all of them to settle (resolve or reject). Promise.all()
does not interfere with nor influence the order/timing of execution of the promise itself.
这篇关于为什么我的 Promises 数组在调用 Promise.all() 之前运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!