Aus*_*rey 5 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 API
var request = require("request");
var resultsArr = new Array();
var options = { method: 'POST',
url: 'blah',
body: '{\n\t"api_key": "********",\n\t"policy_number": "' +clientRecord+ '"\n}' };
request(options, function (error, response, body) {
var resData = JSON.parse(body); //stores json response into object
// Do Work here
return resultsArr;
}
Run Code Online (Sandbox Code Playgroud)
当我在console.log arrayOfResults [0]时,我正确地接收了所有数据.
当我像上面的console.log arrayOfResults [0] [0]一样,我得到了未定义,除非我设置超时以实际等待结果.
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);
});
});
Run Code Online (Sandbox Code Playgroud)
我整理了兰迪为您提供的建议,以便您获得更好的想法,
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |