2

I'm using promise object in node.js. I have a object:

var Send = {
    send(post_ids) {
        return Post.findById(post_ids)
            .then((posts) => {
                return sendArticlesToWechat(setupArticles(posts)); // sendArticlesToWechat is also a promise
            })
            .then((result) => {
                console.log("RESULT: " + result);
            })
            .catch((err) => {
                console.error("SEND ERROR: " + err);
                return err;
            });
        },
}

export default Send;

and call its method in another file:

Send.send(req.body)
    .then((result) => {
        console.log("CALL SEND: " + result);
    })
    .catch((err) => {
        console.error(err);
    });

When an error occurs, I got two output:

SEND ERROR: ERROR: // error message
CALL SEND: ERROR: // error message

This error occurred in the sendArticlesToWechat() function which be returned. Because it's a promise too so I can catch its error outside. This is what I expected.

When I call the Send.send(), I expected to get the error in catch(), but the error appears in the then() method.

According to the output, the error did returned from the previous catch(), why I can not keep it in the catch()?

Brick Yang
  • 5,388
  • 8
  • 34
  • 45

1 Answers1

1

The problem is in your final catch(). Because you return err, you cause the promise to become resolved instead of rejected. If you want to return a rejected promise, then either remove the catch() or re-throw err

var Send = {
    send(post_ids) {
        return Post.findById(post_ids)
            .then((posts) => {
                return sendArticlesToWechat(setupArticles(posts)); // sendArticlesToWechat is also a promise
            })
            .then((result) => {
                console.log("RESULT: " + result);
            })
            .catch((err) => {
                console.error("SEND ERROR: " + err);
                //return err;//converts from reject to resolved
                throw err;
            });
        },
}

export default Send;
pgreen2
  • 3,601
  • 3
  • 32
  • 59
  • yes, it works. Thanks. So which one do you think is better? remove the `catch()` or `throw err`? – Brick Yang Nov 20 '15 at 04:06
  • That can vary, but in this case I would go with `throw err`. I would do the logging in your `Send` object just in case the calling code forgets to write a `catch()`. That way at least the logs will show an error happened. – pgreen2 Nov 20 '15 at 04:11