Reputation: 10228
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()
?
Upvotes: 2
Views: 776
Reputation: 445
BTW, $.ajax
returns jqXHR object that implements the Promise interface, giving them all the properties, methods, and behavior of a Promise.
So your code can look like this
function onResolve () { alert( "$.ajax succeeded" ); }
function onReject () { alert( "$.ajax failed" ); }
// Promise syntax style
$.ajax({
url: path,
type: 'GET',
data: {"name": "value"}
}).then(onResolve, onReject);
// or equivalent jQuery syntax style
$.ajax({
url: path,
type: 'GET',
data: {"name": "value"},
success: onResolve,
error: onReject
});
Upvotes: 2
Reputation: 3844
You can return New Promise
like :
function ajaxDone() {
return new Promise(function (resolve, reject) {
$.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) {
resolve(null);
},
timeout: 20000
});
});
}
and how you can use:
ajaxDone().then(function (resolve) {
if (resolve !== null && resolve !== undefined)
//It is done
else
//not done
});
Upvotes: 1
Reputation: 140
Promise should be used like this :
var promise1 = new Promise(function(resolve,reject){
$.ajax({
url : 'yourUrls',
success : function(data){
resolve(data);
},
error : function(err) {
reject(err);
}
})
});
promise1.then(function(response){
//response is what you resolve in promise
}).catch(function(err){
//err is what you send while you reject inside promise
});
Upvotes: 2