I've seen plenty of advice on how to use callbacks and await with respect to making my asynchronous ajax call be syncronous, but am not succeeding. I have a twist. The function that makes the ajax call is itself asynchronous. Below is my attempt at using a callback. There are no errors, but nothing is written to the console in the for/loop. The purpose of this functionality is to prompt the user to select one or more files, import them into SSRS, and update a tree control with new nodes representing the new files. The import works and the data returned from the ajax call (the new node id) is valid, but it gets lost when I try to use it. Any help will be appreciated.
async function readText(event, multiple, data) {
var fileinfo = new Object();
fileinfo.Name = event.name;
fileinfo.Path = '/' + fullpath;
fileinfo.Replace = !multiple;
fileinfo.Id = selectedId;
array = new Uint8Array(await event.arrayBuffer());
fileinfo.Content = btoa(
new Uint8Array(array)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
);
$.ajax(
{
url: '/ABIReportsSSRS/ImportToSSRS',
type: 'POST',
data: fileinfo,
success: function (data) {
return data;
},
error: function (request, status, error)
{
displayErrorMessage(request);
}
});
}
function importData(multiple) {
input = document.createElement('input');
input.type = 'file';
input.multiple = multiple;
var treeviewObj = document.getElementById('tree').ej2_instances[0];
input.onchange = _ => {
var newNode = [];
for (var i = 0; i < event.target.files.length; i++) {
readText(event.target.files.item(i), multiple, function (data) {
console.log(data);
newNode[i] = { Id: data, Name: event.target.files.item(i).name, Type: 'Resource', Image: '../../images/FA-file.png' }
});
}
if (multiple) {
treeviewObj.addNodes(newNode, selectedId, null);
}
else {
treeviewObj.updateNode(selectedId, event.target.files.item(i).name)
}
};
input.click();
}