1

I'm new to promises and I'm saving multiple items to MongoDB database.

For a single item, I have a function that returns a promise, which rejects when the save to the database failed, or resolves if the save to the database succeeded:

exports.save_single_item = (itemBody, itemId) => {
return new Promise((resolve, reject) => {
    var new_item = new Item(itemBody);
    new_item.save(function (err, savedItem) {
        if (err)
            reject('ERROR');
        else {
            resolve('OK');
        }

    });
  });
};

For multiple items, I have a function that, for each item in the submitted array containing items, calls the function above. For that, I'm using this Promise.all construction:

exports.save_multiple_items = (items) => {
var actions = items.map((item) => { module.exports.save_single_item(item, item.id) });
var results = Promise.all(actions);
results.then((savedItems) => {
    console.log('ALL OK!');
}).catch((error) => {
    console.log('ERROR');

  });
};

The problem is, I'm never hitting the catch block on results.then.catch even though every promise call to save_single_item rejects. It goes straight into the then() block and prints out 'ALL OK'.

I'm getting UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 9): ERROR for every item in the array, even though I'm supposedly(?) catching it at the results.then.catch() block.

What am I missing here?

  • 1
    Try doing a `console.log(actions)` and `console.log(savedItems)`. That will give you an idea where things are going wrong. When things are not working as you expect, some simple debugging steps will often shine some light on what's going on. This is an example of how arrow functions are a more advanced tool that should only be used by people that fully understand how it works. It's not just a syntax shortcut (which seems to make everyone want to immediately use it). It's a more advanced tool that will make bugs if not used properly. – jfriend00 May 12 '17 at 13:26

1 Answers1

3

You are actually generating an array of undefined, because of this:

var actions = items.map((item) => { module.exports.save_single_item(item, item.id) })

If you want an array of promises, you should remove the brackets ("concise function body"):

var actions = items.map((item) => module.exports.save_single_item(item, item.id))

Or do an explicit return from the block ("block function body"):

var actions = items.map((item) => { return module.exports.save_single_item(item, item.id) })

More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body

robertklep
  • 198,204
  • 35
  • 394
  • 381