0

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();
}
  • You've defined `readText` as `async`, which is pointless because you never use `await` inside it. (You *could* use the return value of `$.ajax` as a promise, but you don't, you pass a callback instead). – Quentin Dec 24 '21 at 20:09
  • The `success` callback you pass to `$.ajax` has `return data` which is pointless because jQuery never does anything with the return value from the success function. – Quentin Dec 24 '21 at 20:09
  • You're reading the value of `newNode` before the HTTP response has been processed and the callback called. – Quentin Dec 24 '21 at 20:11
  • You pass a callback function to `readText` as the third argument (`data`) … which you then treat as a string. – Quentin Dec 24 '21 at 20:14

0 Answers0