简体   繁体   English

等待对象内的 promise 解决

[英]Waiting for promises inside the object to resolve

I have an object that has promises as its values.我有一个以 promise 为值的对象。 The object fields could have different types of values such as functions, promises, strings, numbers, or another object.对象字段可以具有不同类型的值,例如函数、承诺、字符串、数字或其他对象。 How do I implement a function which waits for all the promises in the object to resolve?如何实现一个等待对象中所有承诺解决的函数?

 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" // } // } })

You can iterate through the keys of the object and solve the promises.您可以遍历对象的键并解决承诺。

 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); });

In the accepted answer, I was not happy with some things:在接受的答案中,我对某些事情不满意:

  • an error is thrown if one of the fields is null or undefined ;如果其中一个字段为nullundefined ,则会引发错误;
  • the input value cannot be a Promise;输入值不能是 Promise;
  • lack of parallelism of waiting for Promises;缺乏等待 Promise 的并行性;

To fix these things, I changed the function:为了解决这些问题,我更改了函数:

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;
}

Maybe for someone, it will be useful.也许对某人来说,它会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM