How to await the ajax request?
this works for me
async function doAjax() {
const result = await $.ajax({
url: "https://api.exchangerate-api.com/v4/latest/USD",
type: 'GET',
});
return result;
}
async function tt(){
var res = await doAjax()
var money = res.rates.INR
console.log(money)
}
tt()
use of async/await
with a transpilers like Babel to get it working in older browsers. You’ll also have to install this Babel preset and polyfill from npm:
npm i -D babel-preset-env babel-polyfill
Then
function getData(ajaxurl) {
return $.ajax({
url: ajaxurl,
type: 'GET',
});
};
async function test() {
try {
const res = await getData('https://api.icndb.com/jokes/random')
console.log(res)
} catch(err) {
console.log(err);
}
}
test();
or the .then
callback is just another way to write the same logic.
getData(ajaxurl).then((res) => {
console.log(res)
});
Never use async:false
its dangerous, your app might misbehave.
You can use await only when your response returns a promise.
Unfortunately jQuery ajax doesn't return Promise when its completed.
But you can use promise in ajax request and return the promise when its done.
function asyncAjax(url){
return new Promise(function(resolve, reject) {
$.ajax({
url: url,
type: "GET",
dataType: "json",
beforeSend: function() {
},
success: function(data) {
resolve(data) // Resolve promise and when success
},
error: function(err) {
reject(err) // Reject the promise and go to catch()
}
});
});
}
We have converted ajax call into promise so now we can use await.
try{
const result = await asyncAjax('your url');
} catch(e){
console.log(e);
}
Using async: false
is an extremely bad idea, and defeats the whole purpose of using AJAX at the first place — AJAX is meant to be asynchronous. If you want to wait for a response from your script when you make the AJAX call, simply use deferred objects and promises:
var validation = function () {
var numberCheck = $.ajax({
url: 'php/SeeIfNumberExists?number=' + $('#number_inp').val(),
type: "GET"
});
// Listen to AJAX completion
numberCheck.done(function(html) {
var numOfRows = parseInt(html),
textAreaList = $('.text_input'),
finished = false;
// Rest of your code starts here
try {
document.getElementById('failure').hidden = true;
}
catch(e) {
console.log(e.message);
}
// ... and the rest
});
}
// Bind events using jQuery
$('#btn_submit').click(validation);
I see in your code that you are using a mixture of both native JS and jQuery — it helps if you stick to one :)