How to return the response of AJAX (asynchronous) call? Compare Promise, async/await, fetch
Introduction
The task I took recently was to refactor AMD modules in the project. A simple challenge is how to launch a request and return the result from an AMD module. What we expect is our modules can return the result from the HTTP request.
I tried several ways to solve this problem. I can only get a Promise object from most of these methods. I felt frustrated about it.
Finally, I got a solution to return the result from my module. This article shares my experiments and hopes it can help you. The following items were the methods I have tried.
- Promise + AJAX (failed)
- async/await + AJAX (failed)
- fetch (failed)
- AJAX without aync (success)
Use Promise (ES6) — You will only get a Promise object
- The first method I tried was to use AJAX with Promise as the following code.
var res = new Promise(function (resolve, reject) {
$.ajax({url: resourceUrl,
dataType: "script",
success: function (data) {
resolve(resources);
},
error: function (err) {
reject(err);
}…