Chris
Chris

Reputation: 788

How do I use $.when() instead of await in the following function?

I have the following 2 functions:

$(document).on(`dragover drop change`, `.fileUpload`, async function(e) {
    e.stopPropagation();
    e.preventDefault();
    const thisEl = $(this);
    if (thisEl.val() === `` || e.type === `dragover`) {
        return;
    }
    const headerRec = await getCSVHeaderRow(thisEl[ 0 ].files[ 0 ], `,`);
    console.log(`header rec: `, headerRec,headerRec2);
});

function getCSVHeaderRow(file, delim) {
    return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.onload = function(e) {
            let headerRow = [];
            const rows = e.target.result.split(`\r\n`);
            headerRow = rows[ 0 ];
            console.log(`headerrow: `, headerRow, headerRow.split(delim));
            resolve(headerRow.split(delim));
        };

        reader.onerror = reject;
        reader.readAsText(file);
    });
}

I am trying to use $.when() rather than await but the called function returns a promise object rather than the array:

$(document).on(`dragover drop change`, `.fileUpload`, function(e) {
    e.stopPropagation();
    e.preventDefault();
    const thisEl = $(this);
    if (thisEl.val() === `` || e.type === `dragover`) {
        return;
    }
    const headerRec2 = $.when(getCSVHeaderRow2(thisEl[ 0 ].files[ 0 ], `,`)).then(function(data) {
        return data;
    });
    console.log(`header rec: `, headerRec,headerRec2);
});

function getCSVHeaderRow2(file, delim) {
    const dfr = $.Deferred();
    let reader = new FileReader();
    reader.onload=function(e) {
        let headerRow = [];
        const rows = e.target.result.split(`\r\n`);
        headerRow = rows[ 0 ];
        console.log(`headerrow: `, headerRow, headerRow.split(delim));
        return headerRow.split(delim);
    };
    return dfr.resolve(reader.readAsText(file));

}

What do I need to change in getCSVHeaderRow2() to have it return the array in the way getCSVHeaderRow() is?

Upvotes: 0

Views: 26

Answers (0)

Related Questions