One effective approach is to utilize the Promise
and fetch
APIs for asynchronous tasks.
function ajax(options) {
return new Promise(function (resolve, reject) {
fetch(options.url, {
method: options.method,
headers: options.headers,
body: options.body
}).then(function (response) {
response.json().then(function (json) {
resolve(json);
}).catch(err => reject(err));
}).catch(err => reject(err));
});
}
You can implement it as shown below:
const ajaxResponse = await ajax({url: '/some/api/call', method: 'get'});
If you prefer not to use async
functions, you can handle it in the following manner:
ajax({url: '/some/api/call', method: 'get'}).then(data => {
// process data here
});
Clarification:
JavaScript operates on a single thread, causing operations to block execution. By utilizing the asynchronous capabilities of the XMLHttpRequest
and fetch
APIs, code can proceed while waiting for Ajax responses.
In your scenario, no response is obtained because the function continues executing before the Ajax call completes. Managing this asynchronous task with Promises
allows JavaScript to handle the response once available.
The use of async
functions simplifies reading async code by encapsulating the body within a Promise
. Additionally, using await
enables waiting for the completion of a preceding Promise
.
Therefore, code written as:
const call = await ajax({ ... });
console.log(call);
is equivalent to:
ajax({ ... }).then(call => {
console.log(call);
});