I have an ajax request and I need to wait for the response to come back. I'm sure I have to use promises, but I'm really scared of promises and I can never understand it. It has multiple things named .then()
, .resolved()
, .reject()
, .catch()
etc. which makes me confused.
I have to use it anyway. So here is my code which doesn't work:
Promise(function (resolve, reject) {
var req = $.ajax({
url: path,
type: 'GET',
data: {"name": value },
beforeSend: function () {
if (req != null) {
req.abort();
}
},
success: function (url) {
resolve(url);
},
error: function (jqXHR, textStatus, errorThrown) {
reject(textStatus);
},
timeout: 20000
});
});
As far as I know, that an ajax call happens, because when I put console.log(url)
in success
block, it prints the url as well and all fine. But I don't know how can I return it? I mean how resolve()
returns something? And when exactly should I use .then()
?