[英]Waiting for promises inside the object to resolve
我有一个以 promise 为值的对象。 对象字段可以具有不同类型的值,例如函数、承诺、字符串、数字或其他对象。 如何实现一个等待对象中所有承诺解决的函数?
const asyncFunction = () => { return Promise.resolve("Resolved!") } const nonAsyncFunction = () => { return "Resolved!" } const awaitObjectWithPromise = (obj) => { // Returns a promise which waits for all // the promises inside "obj" to be resolved. } let obj = { key1: asyncFunction(), key2: nonAsyncFunction(), key3: "Some Value", parent1: { key1: asyncFunction(), key2: nonAsyncFunction(), key3: "Some Value" } } awaitObjectWithPromise(obj).then((obj) => { console.log(obj); // Should output: // { // key1: "Resolved!", // key2: "Resolved!", // key3: "Some Value", // parent1: { // key1: "Resolved!", // key2: "Resolved!", // key3: "Some Value" // } // } })
您可以遍历对象的键并解决承诺。
const asyncFunction = () => { return Promise.resolve("Resolved!") } const nonAsyncFunction = () => { return "Resolved!" } const awaitObjectWithPromise = async(obj) => { for (let prop in obj) { // If the propriety has a 'then' function it's a Promise if (typeof obj[prop].then === 'function') { obj[prop] = await obj[prop]; } if (typeof obj[prop] === 'object') { obj[prop] = await awaitObjectWithPromise(obj[prop]); } } return obj; } let obj = { key1: asyncFunction(), key2: nonAsyncFunction(), key3: "Some Value", parent1: { key1: asyncFunction(), key2: nonAsyncFunction(), key3: "Some Value" } } awaitObjectWithPromise(obj).then((obj) => { console.log(obj); });
在接受的答案中,我对某些事情不满意:
null
或undefined
,则会引发错误;为了解决这些问题,我更改了函数:
const promiseAll = async (obj) => {
if (obj && typeof obj.then == 'function') obj = await obj;
if (!obj || typeof obj != 'object') return obj;
const forWaiting = [];
Object.keys(obj).forEach(k => {
if (obj[k] && typeof obj[k].then == 'function') forWaiting.push(obj[k].then(res => obj[k] = res));
if (obj[k] && typeof obj[k] == 'object') forWaiting.push(promiseAll(obj[k]))
});
await Promise.all(forWaiting);
return obj;
}
也许对某人来说,它会很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.