typescript和firebase-async等待进行多个调用



我逐行从文件中读取了一些用户记录。每一行都是我创建的用户记录,如果它不存在的话。同一用户记录可以在多行中。所以基本上,如果我看到它已经创建好了,我就跳过。

代码看起来像下面

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(/[rn]+/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)
}
)
})
}

我观察到的是,代码真的不需要等待一行处理。因此,我必须多次运行代码才能导入完整的数据。

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

var t = 0
for (let line of lines){
if (firstLine == false){
firstLine = true
} else{
setTimeout(function(line){ this.createClickHistory(line).then(
(resp)=> console.log("line processed")
)}.bind(this, line), t*16) // 60fps
}
t++
}

相关内容

最新更新