我需要在async
循环中调用for
函数,在该循环中,每次迭代都会“构建”一个对象。在循环结束时,应在Promise
中解析此对象,以便链中的下一个函数可以将其拾取以进行进一步处理。尽管迭代可以正确获取数据,但我无法收集“构建”的对象并将其返回。我不断收到{}
。你能帮我解决这个问题吗?
async function imageDetailsCache(images) {
var imageData = {}; // This object is built up every iteration
var imageNo = '';
var promises = [];
//
for (let i = 0; i < images.length; i++) {
imageNo = images[i]
promises.push(
new Promise(function (resolve, reject) {
imageDetails(imageNo, 'BIG').then(function (result) {
imageData[imageNo] = { 'BIG': result }
imageDetails(imageNo, 'TINY').then(function (result) {
imageData[imageNo] = { 'TINY': result }
})
})
resolve(imageData)
})
)
}
Promise.all(promises).then(function (result) {
return result; // Always {}
})
}
答案 0 :(得分:2)
避免使用Promise
constructor antipattern!您在resolve
中的异步事件发生之前就在呼叫imageDetails
。并且在使用then
/ async
时不要使用await
:
async function imageDetailsCache(images) {
var imageData = {}; // This object is built up every iteration
var promises = images.map(async (image) => {
var result = await imageDetails(image, 'BIG');
imageData[image] = { 'BIG': result }
var result = await imageDetails(image, 'TINY');
imageData[image] = { 'TINY': result };
});
await Promise.all(promises);
return imageData;
}
答案 1 :(得分:0)
如果要使用Promises,则: 我想这会起作用:
MyEnum
}
imageDetailsCache(images).then((r)=> {console.log(r)});
我确实要强调,正确使用async&await(如https://stackoverflow.com/users/1048572/bergi所建议的那样)可以使此代码更简洁。
我个人会这样:
async function imageDetailsCache(images) {
var imageData = {};
var promises = [];
for(let i = 0; i < images.length; i++) { // notice the let instead of var
promises.push(
new Promise( (resolve, reject) => {
imageDetails(images[i], 'BIG')
.catch(e => {reject(e)})
.then( rBig => {
imageDetails(images[i], 'SMALL')
.catch(e => { reject(e)})
.then( rSmall => {
imageData[images[i]] = {
'BIG': rBig ,
'SMALL': rSmall
}
resolve ({
BIG: rBig,
SMALL: rSmall
});
});
});
}
)
);
}
await Promise.all(promises);
return imageData;
}
imageDetailsCache(images).then((r)=> {console.log(r)});
希望有帮助!