Monday, 29 May 2017

Async promises inside loop

I know this is a topic where there is a lot of info, but I still can't solve this.

I am working with NodeJs that connects to a mysql server, I have an array, I need to iterate the array and do some stuff with the data, the thing is I need to do a query to the mysql server but I need to the for loop wait until I got the results of the query, I have tried a lot of things, now I am trying with .each method of bluebird but still is not working properly, this is my code.

the initial function is Notification.getByUser

thanks in advance

'use strict';
var Promise = require("bluebird");

module.exports = function(Notifications) {
  Notifications.execute = function(sql, itemId) {
    return new Promise((resolve, reject) => {
      this.dataSource.connector.execute(sql, (e, result) => {
        console.log('-----RESULT----', itemId);
        console.log(result);
        console.log('-----ERROR-----', itemId);
        console.log(e);
        if (result.length === 0) {
          resolve(false);
        } else {
          resolve(true);
        }
      });
    });
  };
  Notifications.isMatching = function(item, user, type) {
    return new Promise((resolve, reject) => {
      console.log(type, item, user);
      if (item !== null) {
        if (item !== user) {
          resolve(false);
        }
      }

      resolve(true);
    });
  };
  Notifications.getByUser = function(userId, isZolver, countryId, cityId, userState, cb) {
    var where = { status: 1 };
    var plainText = '';
    var items = Notifications.find({ where });
    Promise.each(items, item => {
      return Notifications.isMatching(item.isZolver, isZolver, 'isZolver')
        .then(() => {
          Notifications.isMatching(item.cityId, cityId, 'cityId');
        })
          .then(() => {
            if(item.extraCondition !== null && item.extraCondition !== '') {
              var sql = item.extraCondition.replace(/:user_id/g, userId);
              // console.log(sql);
              Notifications.execute(sql, item.id)
                .then(render => console.log('extraCondition', render));
            } else {
              console.log('extraCondition', true);
            }
          });
    }).then(res => {
      // console.log('res del loop', res);
    });
    cb(null, 'ok');
  };
};


via Grunch

No comments:

Post a Comment