let obj = [
{
Id: 1,
name: 'david',
Address:[{
city: 'dubai',
country: 'UAE'
}]
},
{
Id: 2,
name: 'Ram',
Address: [{
city: 'US',
country: 'India'
},
{
city: 'Delhi1',
country: 'India1'
}]
}
];
async function fun() {
await Promise.all(obj.map(async info => {
console.log('info', JSON.stringify(info));
await Promise.all(info.Address.map(async (items, index) => {
console.log('ParentItems IsParentLossCapability',);
let pr = await firstFunction();
console.log('promise resolved: ' + pr)
console.log('next step');
}));
console.log('UpdatedInfo', JSON.stringify(obj));
}));
}
async function firstFunction() {
return new Promise((resolve, reject) => {
let y = 0;
setTimeout(() => {
for (let i = 0; i < 10; i++) {
y++;
}
console.log('loop completed');
resolve(y);
}, 2000);
});
}
fun();我得到的输出如下,它说
它应该能提供这样的输出,
发布于 2020-09-18 12:14:01
当您使用.map(async (e) => {...})时,所有函数都会同时开始执行。await Promise.all(arr.map(async (e) => {...}))等待它们全部完成,但它仍然是并行的。
你想要的是按顺序排列。可以使用for循环:
for (let info of obj) {
console.log('info', JSON.stringify(info));
for (let index = 0 ; index < info.Address.length; index++) {
let items = info.Address[index];
console.log('ParentItems IsParentLossCapability',);
let pr = await firstFunction();
console.log('promise resolved: ' + pr)
console.log('next step');
}
console.log('UpdatedInfo', JSON.stringify(obj));
}或者使用异步缩减:
await obj.reduce(async (memo, info) => {
await memo;
console.log('info', JSON.stringify(info));
await info.Address.reduce(async (memo2, items, index) => {
await memo2;
console.log('ParentItems IsParentLossCapability',);
let pr = await firstFunction();
console.log('promise resolved: ' + pr)
console.log('next step');
}), Promise.resolve());
console.log('UpdatedInfo', JSON.stringify(obj));
}, Promise.resolve());https://stackoverflow.com/questions/63938251
复制相似问题