如何在 JavaScript 中按顺序解析 Promise 数组
如果使用 JavaScript,无论是浏览器中的普通 JS、React 还是 Node.js,大家可能都熟悉 Promises
。 此外,大家可能还遇到过使用 Promise.all()
函数解析 Promise 数组。
这是 Promise.all()
的示例:
const getSquare = async (x) => Math.pow(x, 2);
const printSquares = async () => {
const nums = [1, 2, 3, 4, 5];
const promiseArray = nums.map(x => getSquare(x));
const resolvedPromises = await Promise.all(promiseArray);
console.log(resolvedPromises);
};
printSquares();
getSquare
返回一个 Promise,并且正如名称所述,promiseArray
包含一个 Promise 数组。 所有这些 Promise 都需要在得到 square 之前解决。 如果你不这样做,将打印到控制台的内容如下:
[
Promise {
1,
[Symbol(async_id_symbol)]: 36,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
},
Promise {
4,
[Symbol(async_id_symbol)]: 37,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
},
Promise {
9,
[Symbol(async_id_symbol)]: 38,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
},
Promise {
16,
[Symbol(async_id_symbol)]: 39,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
},
Promise {
25,
[Symbol(async_id_symbol)]: 40,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
}
]
而不是所需的输出:
[ 1, 4, 9, 16, 25 ]
顺序解析 Promise
在上面的例子中,getSquare
被解析的顺序并不重要…… 请注意,返回数组的元素将始终对应于 Promises 数组。
但是,说顺序确实很重要或进行并行处理会产生系统问题。 例如,我最近遇到了数百次并行调用 Firebase getUser
函数的问题。 有时由于数据库过载而发生 Firestore 错误。
const uids = ["id1", "id2",...];
const userPromises = uids.map(uid => admin
.auth()
.getUser(uid)
.then((userRecord) => {
return userRecord.toJSON();
})
.catch(console.error)
);
const users = await Promise.all(userPromises); // The problem!
幸运的是,处理不是时间敏感或密集的,因此按顺序进行处理是可以接受的。
JavaScript 运行时实际上并不并行处理,也不是多线程的,而是有一个事件循环来执行非阻塞 I/O 操作。 例如,如果 Promise 调用外部 URL,则运行时将在事件循环中处理下一个任务,因为它等待来自被调用 URL 的响应。 这使得处理看起来多线程且快速。 出于这个原因,顺序处理通常要慢得多,因为我们在 Promise 完全完成之前一直处于阻塞状态。
起初,您可能会认为使用 forEach
......不要! forEach 不能很好地与 aysnc
配合使用,并且会导致问题。
但是,ES 2018 版本的 for
非常适合使用 await*
进行顺序处理:
const resolvePromisesSeq = async (tasks) => {
const results = [];
for (const task of tasks) {
results.push(await task);
}
return results;
};
resolvePromisesSeq
将接受一系列任务,然后按顺序处理每个任务。
让我们将 Firebase 代码更新为顺序的:
const uids = ["id1", "id2",...];
const userPromises = uids.map(uid => admin
.auth()
.getUser(uid)
.then((userRecord) => {
return userRecord.toJSON();
})
.catch(console.error)
);
const users = await resolvePromisesSeq(userPromises); // No longer a problem!
完美!
每当我们需要按顺序处理 Promises 时,新函数都是可重用的。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。