Vineet Vineet - 4 months ago 6
Node.js Question

Creating functions to chain promises correctly

I am trying to get Promise chaining working for me correctly.

I believe the problem boils down to understanding the difference between:

promise.then(foo).then(bar);


and:

promise.then(foo.then(bar));


In this situation I am writing both
foo
and
bar
and am trying to get the signatures right.
bar
does take a return value that is produced by
foo
.

I have the latter working, but my question is what do I need to do to get the former working?

Related to the above is the full code (below). I don't have the different logs printed in the order I am expecting (expecting
log1
,
log2
,
log3
,
log4
,
log5
, but getting
log3
,
log4
,
log5
,
log1
,
log2
). I am hoping as I figure the above I will get this working right as well.

var Promise = require('bluebird');

function listPages(queryUrl) {
var promise = Promise.resolve();

promise = promise
.then(parseFeed(queryUrl)
.then(function (items) {

items.forEach(function (item) {
promise = promise.then(processItem(transform(item)))
.then(function() { console.log('log1');})
.then(function() { console.log('log2');});
});

}).then(function() {console.log('log3')})
).then(function() {console.log('log4')})
.catch(function (error) {
console.log('error: ', error, error.stack);
});
return promise.then(function() {console.log('log5');});
};

Answer

What is the difference between promise.then(foo).then(bar); and promise.then(foo.then(bar));?

The second one is simply wrong. The then method takes a callback as its argument, not a promise. That callback might return a promise, so the first one is equivalent to

promise.then(function(x) { return foo(x).then(bar) })

(assuming that foo returns a promise as well).


Your whole code appears to be messed up a bit. It should probably read

function listPages(queryUrl) {
    return parseFeed(queryUrl)
    .then(function (items) {
        var promise = Promise.resolve();
        items.forEach(function (item) {
            promise = promise.then(function() {
                console.log('log1');
                return processItem(transform(item));
            }).then(function() {
                console.log('log2');
            });
        });
        return promise;
    }).then(function() {
        console.log('log3')
    }, function (error) {
        console.log('error: ', error, error.stack);
    });
}
Comments