我有一个用例,我想进行一个异步调用(类似于ajax),然后在该调用的成功块中,我想使用由父级生成的ID在一个循环中进行一系列异步调用呼叫。我的要求是:
示例代码段:
asyncCallA(inputId)
.then(output => {
// inputIdsForChildCalls is the list of inputIds for child async
// calls
inputIdsForChildCalls = [do something with output]
for (let i = 0; i < inputIdsForChildCalls.length; i++) {
asyncCallB(inputIdsForChildCalls[i])
.then(output => {
// do something
})
.catch(error => {
// do something with error
});
}
showSuccessToast("Records created successfully!");
})
.catch(error => {
// do something with error
});
asyncCallA(inputId)
.then(output => {
inputIdsForChildCalls = [do something with output]
Promise.all(inputIdsForChildCalls)
.then(outputs => {
// do something
showSuccessToast("Records created successfully!");
})
.catch(error => {
// do something with error
});
}
})
.catch(error => {
// do something with error
});
asyncCallA(inputId)
.then(output => {
inputIdsForChildCalls = [do something with output]
let syncCalls = [];
for (let i = 0; i < inputIdsForChildCalls.length; i++) {
syncCalls.push(asyncCallB(inputIdsForChildCalls[i]));
}
Promise.all(inputIdsForChildCalls)
.then(outputs => {
// do something
showSuccessToast("Records created successfully!");
})
.catch(error => {
// do something with error
});
})
.catch(error => {
// do something with error
});
确保异步链接发生的最佳选择是使用array.reduce函数下面是相同的示例代码。
如果您不清楚array.reduce和promise如何工作。我建议您参考这篇文章。
https://developers.google.com/web/fundamentals/primers/promises
下面是示例代码,您可以使用。
asyncCallA(inputId)
.then(output => {
// inputIdsForChildCalls is the list of inputIds for child async
// calls
inputIdsForChildCalls = [];
inputIdsForChildCalls.reduce(function(sequence, Id)
{
return sequence.then(function()
{
return asyncCallB(Id);
}).then(function(asyncCallResult)
{
//do something
});
}, Promise.resolve())
})
.then(function()
{
showSuccessToast("Records created successfully!");
})
.catch(error => {
// do something with error
});