Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 661
bodokaiser Avatar asked Sep 17 '12 14:09

bodokaiser


Video Answer


2 Answers

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)

like image 185
tlrobinson Avatar answered Oct 17 '22 14:10

tlrobinson


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/

like image 43
wroniasty Avatar answered Oct 17 '22 12:10

wroniasty