bodokaiser
bodokaiser

Reputation: 15742

How do I do a callback chain with q?

I some problems understanding how to use "q" (https://github.com/kriskowal/q) a promises library for javascript:

var delayOne = function() {
    setTimeout(function() {
        return 'hi';
    }, 100);
};

var delayTwo = function(preValue) {
    setTimeout(function() {
        return preValue + ' my name';
    }, 200);
};

var delayThree = function(preValue) {
    setTimeout(function() {
        return preValue + ' is bodo';
    }, 300);
};

var delayFour = function(preValue) {
    setTimeout(function() {
        console.log(preValue);
    }, 400);

};

Q.fcall(delayOne).then(delayTwo).then(delayThree).then(delayFour).end();

this only returns undefined...

Upvotes: 8

Views: 4753

Answers (2)

tlrobinson
tlrobinson

Reputation: 2858

As wroniasty pointed out, you need to return a promise from each of those functions, but you should also abstract any callback oriented APIs (like setTimeout) as much as possible and use APIs that return promises instead.

In the case of setTimeout, Q already provides Q.delay(ms) which returns a promise that will be resolved after the specified number of milliseconds, perfect for replacing setTimeout:

var delayOne = function() {
    return Q.delay(100).then(function() {
        return 'hi';
    });
};

var delayTwo = function(preValue) {
    return Q.delay(200).then(function() {
        return preValue + ' my name';
    });
};

var delayThree = function(preValue) {
    return Q.delay(300).then(function() {
        return preValue + ' is bodo';
    });
};

var delayFour = function(preValue) {
    return Q.delay(400).then(function() {
        console.log(preValue);
    });
};

Q.fcall(delayOne).then(delayTwo).then(delayThree).then(delayFour).done();

(note: end has been replaced with done)

Upvotes: 12

wroniasty
wroniasty

Reputation: 8052

The reason you get "undefined" is because the functions you are chaining are not returning anything:

var delayOne = function() {
  setTimeout(function() {
    return 'hi';
  }, 100);
};

delayOne calls setTimeout, and returns nothing (undefined).

To achieve your goal you must use Q.defer:

var delayOne = function() {
  var d = Q.defer();    
  setTimeout(function() {
    d.resolve("HELLO");
  }, 100);
  return d.promise;
};

var delayTwo = function(preValue) {
   setTimeout(function() {
     alert(preValue);
   }, 
   400);
};

delayOne().then ( delayTwo );

http://jsfiddle.net/uzJrs/2/

Upvotes: 9

Related Questions