gpt4 book ai didi

javascript - 具有嵌套 Promise 数组的对象

转载 作者:行者123 更新时间:2023-12-03 02:42:55 24 4
gpt4 key购买 nike

我有一个带有嵌套 promise 数组的对象。

 let promise = new Promise(resolve => setTimeout(resolve, 1000, 'url'));
let object = {
registration: [promise, promise, promise],
contract: [promise, promise, promise],
businessLicense: [promise, promise, promise],
businessPlan: [promise, promise, promise]
};

我需要一个使用 Promise.all 给出以下结果的函数

   resolvePromisesFunction(object).then(result => console.log(result))

// the output should be
{
registration: [ 'url', 'url', 'url' ],
contract: [ 'url', 'url', 'url' ],
businessLicense: [ 'url', 'url', 'url' ],
businessPlan: [ 'url', 'url', 'url' ]
}

谢谢!

最佳答案

您可以使用chaining promises与 Promise.all 一起:

let promise = new Promise(resolve => setTimeout(resolve, 1000, 'url'));
var obj = {
registration: [promise, promise, promise],
contract: [promise, promise, promise],
businessLicense: [promise, promise, promise],
businessPlan: [promise, promise, promise]
};

function resolvePromisesFunction(obj) {
let resolvedObj = {};
return Promise.all(Object.keys(obj).map(service => {
return Promise.all(obj[service])
.then(result => resolvedObj[service] = result);
})).then(result => resolvedObj);

}

resolvePromisesFunction(obj).then(result => console.log(result));

关于javascript - 具有嵌套 Promise 数组的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48244445/

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