Promise Jquery examples

by Soviut

HTML

<script src="https://rawgit.com/kriskowal/q/v1/q.js"></script>

JavaScript

function getUsers() {
    console.log('getting users');
    return $.ajax({
        url: '/echo/json/',
        type: 'POST',
        data: {
            json: '{"users": ["Ian", "Gino", "Michala", "Marshall", "Shigeo", "Steve"]}',
            delay: 2
        }
    });
};

var usersPromise = getUsers();

usersPromise.then(function(data) {
    console.log('success', data);
}, function(err) {
    console.log('failure', err);
});

function getProfile(data) {
    console.log('getting profile for ' + data.users[0]);
    // need to return a promise to chain in jquery
    return $.ajax({
        url: '/echo/json/',
        type: 'POST',
        data: {
            json: '{"first": "Ian", "last": "Zamojc", "cool": true}',
            delay: 2
        }
    });
};
// chaining
usersPromise
    .then(getProfile) // call external function
    .done(function(data) {
        console.log('complete', data);
        var confirmation = data.cool ? 'is' : "isn't";
        console.log('' + data.first + ' ' + data.last + ' ' + confirmation + ' cool');
    });