gpt4 book ai didi

javascript - 等效于 ES6 Promises 的 BlueBird Promise.props?

转载 作者:数据小太阳 更新时间:2023-10-29 05:35:03 39 4
gpt4 key购买 nike

我想等待 Promise 的单词映射完成。 BlueBird 有 Promise.props 可以实现这一点,但是有没有一种干净的方法可以在常规 javascript 中做到这一点?我想我可以创建一个包含单词和 Promise 的新对象,获取这些对象的 Promise 数组,然后调用 Promise.all 并将它们放入 map 中,但这似乎有点矫枉过正。

最佳答案

适用于普通对象的 Bluebird.props 实现:

/**
* This function maps `{a: somePromise}` to a promise that
* resolves with `{a: resolvedValue}`.
* @param {object} obj
* @returns {Promise<object>}
*/
function makePromiseFromObject(obj) {
const keys = Object.keys(obj);
const values = Object.values(obj);
return Promise.all(values)
.then(resolved => {
const res = {};
for (let i = 0; i < keys.length; i += 1) {
res[keys[i]] = resolved[i];
}
return res;
})
}

关于javascript - 等效于 ES6 Promises 的 BlueBird Promise.props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44600771/

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