Skip to content

Instantly share code, notes, and snippets.

@pbojinov
Last active August 31, 2022 02:38
Show Gist options
  • Select an option

  • Save pbojinov/ca377fd51c69531a8029 to your computer and use it in GitHub Desktop.

Select an option

Save pbojinov/ca377fd51c69531a8029 to your computer and use it in GitHub Desktop.
simple jQuery Deferred example
function getData() {
var deferred = $.Deferred();
$.ajax({
'url': 'http://google.com',
'success': function(data) {
deferred.resolve('yay');
},
'error': function(error) {
deferred.reject('boo');
}
});
return deferred.promise();
}
$.when(getData()).done(function(value) {
alert(value);
});
getData().then(function(value) {
alert(value);
});
@camainc

camainc commented Mar 28, 2019

Copy link
Copy Markdown

Thanks for this!

@sharathcv

Copy link
Copy Markdown

Thank you!

@devellopah

Copy link
Copy Markdown

thanks, just one note: for testing purposes it would be better to use 'url': window.location.origin or one may come across cross-origin request issue

ghost commented Dec 23, 2019

Copy link
Copy Markdown

$.ajax already returns a deferred/promise.

function getData() {
    return $.ajax({
        'url': 'http://foo.com',
        'success': function(data) {
            return data;
        },
        'error': function(error){
            console.log("An error occurred:", error);
        }
    });
}

$.when(getData).then(function(value) {
    if(value){
        alert(value);
    } else {
         console.log("Successful ajax call, but no data was returned");
    }
});

@pbojinov

Copy link
Copy Markdown
Author

@jeremyroelfs thank you for the clarification, this was me attempting to learn and document some commonly used patterns but obviously my understanding at the time wasn't correct

ghost commented Dec 24, 2019

Copy link
Copy Markdown

I think its awesome you doing gists of your work! Keep it up man! That helps others!!!

@ydarwin

ydarwin commented Aug 30, 2022

Copy link
Copy Markdown

Complete example!

function getData() {
    var deferred = $.Deferred();

    $.ajax({
        'url': 'http://google.com',
        'success': function(data) {
            deferred.resolve('yay');
        },
        'error': function(error) {
            deferred.reject('boo');
        }
    });

    return deferred.promise();
}

$.when(getData()).done(function(value) {
    alert(value);
});

getData().then(
function(value) {
	alert(value);
},
function (error) {
    alert(error);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment