在继续循环之前等待Firebase响应

时间:2019-08-15 14:56:46

标签: firebase firebase-realtime-database ionic4

我正在构建一个类似uber的应用,我想向我数据库中的驱动程序一个发送一个行程请求,并等待该驱动程序的响应,然后再将该请求发送给下一个驱动程序(如果该行程被拒绝),或者结束循环(如果接受旅行)。

我试图在从数据库中获得的所有驱动程序上使用for循环,然后发送请求然后进行侦听,但没有得到期望的结果。而是将请求发送到所有驱动程序。

   sendTripRequest(request){
    this.rejecters = [];
    // var i = 0;
    // var inProgress = false;
    Object.keys(this.allDrivers).forEach((key)=>{
      // put all drivers into an array
      this.allDriversAray.push(this.allDrivers[key])
    })

    // sort all drivers by distance and put in another array
    this.sortedDriversAray = this.applyHaversine(this.allDriversAray,request.originLat,request.originLng);
    this.sortedDriversAray.sort((locationA,locationB)=>{
      return locationA.distance - locationB.distance;
    });
    // send request to drivers starting from closest
    return new Promise((resolve,reject)=>{
      console.log('sorted array is ');
      console.log(this.sortedDriversAray);

        for(let i = 0;i<this.sortedDriversAray.length;i++){  
          console.log('handling driver: '+this.sortedDriversAray[i].id);

          // while(inProgress);  
          // inProgress = true;   

          if(this.sortedDriversAray[i].availability === true && this.rejecters.indexOf(this.sortedDriversAray[i]) <= -1 && this.sortedDriversAray[i].request == undefined){
            console.log('driver '+this.sortedDriversAray[i].id + ' is available and hasnt rejected,sending request')

                this.driversRef.child(`${this.sortedDriversAray[i].id}`).update({ request: request }).then(()=>{
                  // watch driver and update changes
                  this.driversRef.child(`${this.sortedDriversAray[i].id}`).on("value",response=>{
                    let driverResponse = response.val().request
                    if(driverResponse == undefined){
                      console.log('driver '+this.sortedDriversAray[i].id+' just rejected,adding him to array');
                      this.rejecters.push(this.sortedDriversAray[i].id);
                      console.log(this.rejecters);
                      // inProgress = false;
                    }else if(driverResponse.accepted == true){
                      console.log('yay! driver '+this.sortedDriversAray[i].id+' just accepted');
                      // this.trackDriver(closestDriver.id)
                      // resolve(true) 
                    }
                  })
                })
            }else{
            console.log('no drivers found')
            this.loadingCtrl.dismiss();
            resolve('no driver found')
            }
      }
    })

  }

我希望函数首先发送到已排序数组中的第一个驱动程序,等待他的响应,如果它被拒绝(即请求被删除,现在未定义),然后发送给下一个驱动程序,如果被接受,则停止循环...请帮助

1 个答案:

答案 0 :(得分:0)

for循环将不起作用,因为正如您所发现的那样,它只会将它们全部触发。

相反,我认为您需要一个递归函数。

这只是一个简单的想法,显然我无法编译它,所以我不知道它是否有效,只是为了给您一个概念:

askNextDriver(sortedDriversAray, i) {
    console.log('handling driver: '+sortedDriversAray[i].id);

    // while(inProgress);  
    // inProgress = true;   

    if(sortedDriversAray[i].availability === true && this.rejecters.indexOf(sortedDriversAray[i]) <= -1 && sortedDriversAray[i].request == undefined){
      console.log('driver '+sortedDriversAray[i].id + ' is available and hasnt rejected,sending request')

          this.driversRef.child(`${sortedDriversAray[i].id}`).update({ request: request }).then(()=>{
            // watch driver and update changes
            this.driversRef.child(`${sortedDriversAray[i].id}`).on("value",response=>{
              let driverResponse = response.val().request
              if(driverResponse == undefined){
                console.log('driver '+sortedDriversAray[i].id+' just rejected,adding him to array');
                this.rejecters.push(sortedDriversAray[i].id);
                console.log(this.rejecters);

                // ASK NEXT DRIVER
                if(i < sortedDriversAray.length) {
                    this.askNextDriver(sortedDriversAray, i++);
                }
                // END ASK NEXT DRIVER

                // inProgress = false;
              }else if(driverResponse.accepted == true){
                console.log('yay! driver '+sortedDriversAray[i].id+' just accepted');
                // this.trackDriver(closestDriver.id)
                // resolve(true) 
              }
            })
          })
      }else{
      console.log('no drivers found')
      this.loadingCtrl.dismiss();
      resolve('no driver found')
      }
}

因此,当您拥有初始驱动程序列表时就将其启动,然后在每次驱动程序出现故障时,它都会检查是否还有其他驱动程序,然后自行调用:

                // ASK NEXT DRIVER
                if(i < sortedDriversAray.length) {
                    this.askNextDriver(sortedDriversAray, i++);
                }
                // END ASK NEXT DRIVER