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?
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. Eg the catch
clause will also be invoked if requestDidSucceed
throws an error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.