簡體   English   中英

等待對象內的 promise 解決

[英]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); });

在接受的答案中,我對某些事情不滿意:

  • 如果其中一個字段為nullundefined ,則會引發錯誤;
  • 輸入值不能是 Promise;
  • 缺乏等待 Promise 的並行性;

為了解決這些問題,我更改了函數:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM