7th May, 2014

Testing deferred promise chains

//
// Demonstration of chaining deferred promises together 
//

var Q = require('q');


function firstFunction () {
    var deferred = Q.defer();

    console.log('About to set timeout');

    setTimeout(deferred.resolve, 1000);

    console.log('Timeout set. Now resolving the promise');

    return deferred.promise;
}


function resolveFunction () {
    console.log('Then now executed');

    var deferred = Q.defer();

    console.log('About to set SECOND timeout');

    setTimeout(deferred.resolve, 2000);

    console.log('SECOND Timeout set. Now resolving the promise');

    return deferred.promise;
}


function secondResolveFunction () {
    console.log('secondResolveFunction executed');
}


var promise = firstFunction();
console.log('We now have a promise object, let\'s execute then');

promise
    .then(resolveFunction)
    .then(secondResolveFunction);

 

The opinions expressed here are my own and not those of my employer.