Typescript和Firebase异步等待进行多个调用

时间:2018-12-01 00:24:11

标签: typescript firebase firebase-realtime-database async-await

我正在从文件行读取少量用户记录。并且每行都是我创建的用户记录(如果不存在)。同一条用户记录可以位于多行中。所以基本上,如果我看到它已经创建,那么我就跳过。

代码如下所示

async onFilesAdded(files: FileList){
    this.fileToUpload = files.item(0);

    let fileReader = new FileReader();
    fileReader.onload = async (e) => {
     this.showProgress = true
      var lines = fileReader.result.toString().split(/[\r\n]+/g); // tolerate both Windows and Unix linebreaks
      this.totalLines = lines.length
      var firstLine = false

      this.dcSvc.getPageImages().then(
        (resp) => {
          console.log("resp in getPageImage" + JSON.stringify(resp))
          this.pageMap = resp
          this.lineCount = 0
          for(let line of lines){
            if(firstLine == false){
              firstLine = true
            }else{
               this.createClickHistory(line).then(
                 (resp)=> console.log("line processed")
               )
            }
          }
        }
      )
    }

    fileReader.readAsText(this.fileToUpload);
  }


 async createClickHistory(line:string){
        var lineArr = line.split(',')
        const userName = lineArr[1]

           this.dcSvc.getUser(userName).then(
             (res:any) => {
                         console.log("Response of get user is:::" + JSON.stringify(res))
                         if(res.length == 0 ){
                           //user does not exist in the DB
                           console.log("user:" + userName + " does not exist so creating it")
                           const userPayload = {
                                                 "userName": userName
                                               }

                                               this.dcSvc.createUser(userName, userPayload).then((rsp) => {})

                         }else{
                           //user exists so skip
    }
    }

     createUser(userName:string, userPayload){
        return this.db.object("/users/" + userName).set(userPayload)
      }

      getUser(userName:string){
        return new Promise((resolve, reject) => {
                  this.db.list('/users', 
                      ref => ref.orderByChild("userName").equalTo(userName)
                  ).snapshotChanges().subscribe(
                    (res) =>  {
                                resolve(res)
                              }
                  )
                })

      }

我正在观察的是,代码实际上并不等待一行处理。因此,我必须多次运行代码,才能导入完整的数据。

1 个答案:

答案 0 :(得分:0)

您可以使用超时来延迟行的读取:

org.springframework.*