Search code examples
javascriptjquerypromiseasync-awaites6-promise

Failed conversion from promise syntax for jQuery ajax function to try/catch/finally and async/await?


The jQuery code below works well.

// Make request.
$.ajax(settings)
.done(function(result) {
    requestDidSucced(result);
})
.fail(function(result) {
    requestDidFail(result);
})
.always(function(result) {
    requestDidFinish(result);
});

However, converting this code to use try/catch/finally and async/await fails because the finally block doesn't have access to the result of $.ajax().

In particular, if we define result outside the try block, is it safe to assume result gets a value with the finally block like it did with the always block?

// Make request.
try {
    let result = await $.ajax(settings);
    requestDidSucceed(resultBox, result);
} catch (result) {
    requestDidFail(result);
} finally {
    requestDidFinish(result); // This fails because `request` is not available.
}

Is it possible for the finally block to access the result of the AJAX query?


Solution

  • Declare result outside of the try block:

    // Make request.
    let result;
    try {
        result = await $.ajax(settings);
        requestDidSucceed(resultBox, result);
    } catch (error) {
        requestDidFail(error);
    } finally {
        requestDidFinish(result);
    }
    

    However, you should be careful how you arrange this. E.g. the catch clause will also be invoked if requestDidSucceed throws an error.