在完成所有异步,嵌套的$。每个数据库调用之后执行操作

问题描述 投票:0回答:1

我正在尝试在1)所有循环都完成并且2)这些循环内的所有数据库调用完成之后运行函数。

我的数据库调用函数(segmentDatabaseCallstepDatabaseCall)都接受一些参数,解决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
        }
      })
    })
  })
})

数据库调用:

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地图来做到这一点,但我无法解决。

javascript jquery asynchronous promise each
1个回答
0
投票

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中了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.