如何让异步/等待来等待我的嵌套数组填充

时间:2019-01-21 05:30:21

标签: javascript json ecmascript-6

我遇到一个问题,可以看到数组和“ arrayOfResults”的数据,但是当我尝试访问数组的某个部分时,它说未定义。我知道它与异步调用有关,因为如果我将console.log设置为超时,它将正确显示。一般而言,我对异步调用还很陌生,更不用说等待了。感谢您的帮助!

async function convertToCSV() {
        var userInput = document.getElementById("policyList").value; //value from text area
        var arrayOfUserInput = userInput.split('\n').map(str => str.replace(/\s/g, '')); //converts userInput to array and removes whitespace
        var arrayOfResults = new Array();

        //iterates for how many user inputs are recorded into arrayOfUserInput
        for(i = 0; i < arrayOfUserInput.length; i++){
       //awaits for each result of retrieve data before inputing into arrayofresults
         arrayOfResults[i] = await retrieveData(arrayOfUserInput[i]);

        }
        //*****THIS IS THE PART NOT WORKING CORRECTLY****
       console.log(arrayOfResults[0][0]);
     }

     async function retrieveData (clientRecord){
        //pulling data from retrieve_policy API
        var request = require("request");
        var resultsArr = new Array();
        var options = { method: 'POST',
        url: 'https://alamance.britecorepro.com/api/v2/policies/retrieve_policy',
        body: '{\n\t"api_key": "7f37b0b074cedffe559b8fabc0244*****e52bff6eb31205e9d9f442",\n\t"policy_number": "' +clientRecord+ '"\n}' };

        request(options, function (error, response, body) {

        var resData = JSON.parse(body);   //stores json response into object

        //checks to see if record exists, if not then it stores API provided error message
        if(resData.data.policy_number !== undefined){
           var credCheckLength = resData.data.active_revision.named_insureds[0].credit_reports.length //holds array length of credit checks
           var policyNumber = resData.data.policy_number; //policy number
           var name = resData.data.active_revision.named_insureds[0].name; //name
           var creditScore = resData.data.active_revision.named_insureds[0].credit_reports[credCheckLength-1].score; //credit score
           var creditCheckDate = resData.data.active_revision.named_insureds[0].credit_reports[credCheckLength-1].date_updated; //date,time credit score updated
           resultsArr[0]=policyNumber, resultsArr[1]=name, resultsArr[2]=creditScore, resultsArr[3]=creditCheckDate; //to insure proper order on return
        }
        else{
           resultsArr[0] =resData.messages[0];
        }
        });
        return  resultsArr;

     }

当我console.log arrayOfResults [0]时,我正确接收了所有数据。

当我像上面那样console.log arrayOfResults [0] [0]时,除非我超时等待实际结果,否则我将无法定义。

2 个答案:

答案 0 :(得分:1)

    return new Promise(function(resolve, reject) {
        request(options, function (error, response, body) {

        var resData = JSON.parse(body);   //stores json response into object

           if(resData.data.policy_number !== undefined){
             //...........
           } else{
               resultsArr[0] =resData.messages[0];
           }
           resolve(resultsArr);
        });
    });

我整理了兰迪(Randy)为您提供的更好建议的建议

答案 1 :(得分:-1)

为弄清这一点,下面是一个简单的示例,其中采用了更生动的异步/等待方式。

async function addOneInArray() {
  let arr = [1, 2, 3, 4, 5];
  let sumArr = new Array();
  for (let i = 0; i < arr.length; i++) {
    sumArr[i] = await add(arr[i]);
  }
  return sumArr;
}

function add(number) {
  return new Promise((resolve, reject) => {
    setTimeout(() => { resolve(number + 1) }, 100)
  })

}

addOneInArray().then((result)=>{
    console.log("Sum element of an Array by 1 - ",result);
});