TypeScript 结合多个 Promise 等待
我基本上有一个代码,其中我有一个变量,可以合并多个承诺等待,并将它们凝结到一个对象中
const traversals = (await traverseSchemas({filename:"my-validation-schema.json"}).concat([
_.zipObject(
["id-1", "id-2"],
[
await loadSchema({
filename: "schema-1.json"
}),
await loadSchema({
filename: "schema-2.json"
}),
]
),
]);
travereschemas
返回数组对象[{“ key1”:{object}}}:{object}}} ,{“ key2”:{object}}]
我正在探索我是否可以在travers
级别上应用等待,只是以获取所有应许的满足数据或是否有任何保证重构代码的更好方法。
I have basically a piece of code where I have a variable that consolidates multiple promise awaits and concat them into a single object
const traversals = (await traverseSchemas({filename:"my-validation-schema.json"}).concat([
_.zipObject(
["id-1", "id-2"],
[
await loadSchema({
filename: "schema-1.json"
}),
await loadSchema({
filename: "schema-2.json"
}),
]
),
]);
The traverseSchemas
returns an array object [{"key1":{object}}, {"key2": {object}}]
I am exploring if there is a away I can apply await at traversals
level only to get all the promised fulfilled data or if there is any better way to refactor the code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为没有一个 Promise 依赖于另一个 Promise 的结果,所以您可以使用
Promise.all
同时(并行)执行所有 Promise。这只使用单个await
,并且return ...
是一个结合等待值的纯同步表达式 -如果您有权访问顶级
await
code> 或者这已经是另一个async
函数的一部分,您可以定义const traversals = ...
而不是使用return
-Because no promise depends on the result of another, you can execute all of them simultaneously (in parallel) using
Promise.all
. This only utilizes a singleawait
and thereturn ...
is a purely synchronous expression combining the awaited values -If you have access to top-level
await
or this is already part of anotherasync
function, you can defineconst traversals = ...
instead of usingreturn
-有很多选择。
通常,普通代码更容易理解。因此,我会去做这样的事情:
如果您想并行等待等待,可以先准备它们,然后通过 promise.all ,然后加入:
There are many options.
Typically plain code is easier to understand. So I would go for something like this:
If you want to parallelize awaits, you could prepare them first, then request via Promise.all and then join together: