我有一个带有嵌套的promises数组的对象。
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' ]
}
THX!
答案 0 :(得分:1)
您可以将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));

答案 1 :(得分:0)
尝试迭代已知的承诺,Promise.all
,然后Promise.all
结果。
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]
};
const promises = [];
Object.keys(object).forEach(key => {
promises.push(Promise.all(object[key]));
});
Promise.all(promises).then(result => {
const returnedObject = {};
result.forEach((value, index) => {
returnedObject[Object.keys(object)[index]] = value;
});
console.log(returnedObject);
});

答案 2 :(得分:0)
这是一个解析深层嵌套对象递归的方法。寻找所有承诺没有其他对象或阵列的深度
// Resolves array
const promiseMap = (promiseList, functor) =>
Promise.all(promiseList.map(promiseOrValue =>
Promise.resolve(promiseOrValue).then(functor)
))
// Resolves objects
const promiseProps = obj =>
Promise.all(Object.keys(obj).map(key =>
Promise.resolve(obj[key]).then(val => {
obj[key] = val;
})
)).then(() => obj)
// Resolves recrusive deep objects
const resolveNestedPromises = obj =>
Promise.resolve(obj).then(obj => {
if (Array.isArray(obj)) {
return promiseMap(obj, obj => resolveNestedPromises(obj));
}
else if (obj && typeof obj === 'object' && obj.constructor === Object) {
const obj2 = {};
for(const key in obj) {
obj2[key] = resolveNestedPromises(obj[key]);
}
return promiseProps(obj2);
}
return obj;
})
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]
};
promiseProps(object).then(console.log) // or
resolveNestedPromises(object).then(console.log)