我试图在 1) 所有循环完成和 2) 这些循环中的所有数据库调用完成后运行一个函数。
我的数据库调用函数(segmentDatabaseCall
和 stepDatabaseCall
)都采用一些参数、解析 Promise 并在调用完成后发送数据。这是我的代码的(非常)简化版本:
let localData = {}
segmentDatabaseCall(argument) // Call the database
.then(segmentResult => { // Returns trip segments (array of objects)
$.each(segmentResult, (segmentIndex, segmentValue) => { // For each trip segment...
localData['something'] = segmentValue.something // Add some data to local data
stepDatabaseCall(segmentValue.segment_id) // Call the database once per trip segment...
.then(stepResult => { // Returns trip steps (array of objects)
$.each(stepResult, (stepIndex, stepValue) => { // For each trip step...
localData['something'][i]['something_else'] = stepValue.something_else // Add some data to local data
// THIS DOESN'T WORK
const segsDone = segmentIndex >= segmentResult.length - 1;
const stepsDone = stepIndex >= stepResult.length - 1;
if (segsDone && stepsDone) {
// This if statement runs before all calls are finished 1 out of 3 times roughly
}
})
})
})
})
数据库调用:
function databaseCall (argument) {
return new Promise((resolve, reject) => {
$.ajax({
url: $phpUrl,
type: 'post',
data: {
'argument': argument
}
})
.done (function (data) {
var resultJson = JSON.parse(data)
resolve(resultJson)
})
.fail (function (error) {
reject(error)
})
})
}
我尝试使用答案 here ,但它在所有调用完成之前运行,有三分之一的时间。我一定错过了那里的一些柜台吗?
我还认为有一种方法可以使用 Promise 映射来做到这一点,但我无法理解它。
最佳答案
Rxjs 中有一个叫做 forkJoin 的东西。据我了解您的问题,您可以将其用于您的实现。
forkJoin(
this._myService.makeRequest('Request One', 2000),
this._myService.makeRequest('Request Two', 1000),
this._myService.makeRequest('Request Three', 3000)
)
.subscribe(([res1, res2, res3]) => {
this.propOne = res1;
this.propTwo = res2;
this.propThree = res3;
});
阅读更多内容 here 。
关于javascript - 在所有异步、嵌套、$.each 数据库调用完成后执行某些操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60307359/