如何使用wait / async等到JavaScript中的其他功能完成?

时间:2019-08-19 10:21:30

标签: javascript

我具有以下功能。我试图逐行读取csv文件,并尝试同时获取帐户详细信息,如下所示。

async function Upload() {
            var fileUpload = document.getElementById("fileUpload");
            var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
            if (regex.test(fileUpload.value.toLowerCase())) {
                if (typeof (FileReader) != "undefined") {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        var csv = e.target.result;
                        var data = $.csv.toObjects(csv);                    
                        var investorsBalance = "";
                        for(var i=0;i<data.length;i++){
                            investorsBalance = await getAccountDetailsInvestor(data[i].investor_id,data[i].asset_code).then(ret_val => {
                                alert("ret_val :"+ret_val);
                                investorsBalance = ret_val;
                            })
                            alert("investorsBalance :"+investorsBalance)                                                    
                        }                   
                    }
                    reader.readAsText(fileUpload.files[0]);                                                             
                } else {
                    alert("This browser does not support HTML5.");
                }
            } else {
                alert("Please upload a valid CSV file.");
            }                   
        }

async function getAccountDetailsInvestor(investorId,assetCode){
    var investorsBalance = "";
    console.log("getAccountDetails :"+investorId);
    $("#overlay").show();
    var accountKeys = "";
    var userLoadAccount = "";
    userLoadAccount = await server.loadAccount(investorId);
    var data = userLoadAccount.balances;            
    var count = 1;
    var tempData = "";                      
    data.forEach(function(obj){
        var res = (obj.asset_type =="native");
        if(!res){
            if(obj.asset_code == assetCode){
                investorsBalance = obj.balance
            }
        }
    })          
    $("#overlay").hide();   
    return investorsBalance;
}

我遇到了错误。

Uncaught SyntaxError: await is only valid in async function

我要等到getAccountDetailsInvestor()函数完成。怎么做?

2 个答案:

答案 0 :(得分:1)

您需要将reader.onload = async function (e)...回调函数标记为异步

答案 1 :(得分:1)

问题出在这部分:

reader.onload = function(e) {
    var csv = e.target.result;
    var data = $.csv.toObjects(csv);                    
    var investorsBalance = "";
    for(var i=0;i<data.length;i++){
        // You cant use await in a non-async function
        // You also cant use await
        investorsBalance = await getAccountDetailsInvestor(data[i].investor_id,data[i].asset_code)
        // And .then() in the same statement
        .then(ret_val => {
            alert("ret_val :"+ret_val);
            investorsBalance = ret_val;
        })
        alert("investorsBalance :"+investorsBalance)                                                    
    }                   
}

您有两个选择。

1)像这样使onload函数异步:

reader.onload = async function(e) {
   // ... your code           
}

并删除.then()处理程序(因为在异步函数中,await是您的then(),而try/catch是您的catch()):

investorsBalance = await getAccountDetailsInvestor(data[i].investor_id,data[i].asset_code)

// No need for .then() - just use the returned variable
alert("ret_val :" + investorsBalance); 
investorsBalance = investorsBalance ;
alert("investorsBalance :"+investorsBalance)  

2)像这样处理不带await的异步函数:

// No need for await - just handle it with the callback function then()
investorsBalance = getAccountDetailsInvestor(data[i].investor_id,data[i].asset_code)
.then(ret_val => {
   alert("ret_val :" + ret_val);
   investorsBalance = ret_val;
   alert("investorsBalance :"+investorsBalance)  
})