jeudi 13 août 2015

Node.js bluebird.map unexpected result

I've been working with node.js and I need to check an array with jsons and update some of the items and in the end return the updated array. What I'm doing is something like the following: (The main app uses express and sequelize)

exports.getDetails = function (req, res) {
  var accountsArray = [];

  bluebird.map(req.accounts, function(account, callback){
     if (account.type == 'A'){
         if (account.param == req.body.paramSearch){
            account.updateAttributes({
                   param: req.body.paramSearch
            }).then(function(updatedAccount){
                console.log('A type entry');
                accountsArray.push(updatedAccount);
            });
         }
         else{
            console.log('A type entry');
            accountsArray.push(account);
         }
     }
     if (account.type == 'B'){
         if (account.param == req.body.paramSearch){
            account.updateAttributes({
                   param: req.body.paramSearch
            }).then(function(updatedAccount){
                console.log('B type entry');
                accountsArray.push(updatedAccount);
            });
         }
         else{
            console.log('B type entry');
            accountsArray.push(account);
         }
     }
  }).then(function(){
     console.log('Bluebird.map done');
     res.status(200).json({
        data: {
           accounts: accountsArray
        }
     });
  });

What I intended it to do was to first add all the accounts (victims of update or not) to the accountsArray and only then return the json with the accountsArray.

Instead what I get is an empty accountsArry. I used the console.logs in the code to follow how things where being processed. What I always get is something like

Bluebird.map done
A/B type entry
...
A/B type entry

The expected was

A/B type entry
...
A/B type entry
Bluebird.map done

I'm new to node.js and this asynchronous processing still gets me confused. Is there anyway to ensure that I've finished the subfunctions inside the map part and only then move on to the response? If possible, using Bluebird.

Any help is dearly appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire