Tuesday 9 May 2017

Orchestrating promise returns

I have Node 7 application using soap-as-promised (Node SOAP library with promises) and Sequelize to update records in a Postgress database. The Promise.all results is giving me everything correctly. But I cannot figure out how to get the corresponding application in the SOAP client's then scope.

I have some experience with Javascript promises but I just am not getting something.

const Applications = require('./models/applications');
const soap = require('soap-as-promised');
const config = require('../../config');
const request = require('request');
const _ = require('lodash');

module.exports = function () {
   Promise.all([soap.createClient(validator.wsdl, {
    request: request.defaults({
      auth: {
        user: validator.user,
        pass: validator.pass,
      },
    }),
    forceSoap12Headers: true,
  }), Applications.findAll({
    where: {
      is_valid: false,
    }
  })])
    .then((results) => {
      const client = results[0];  // This is the resolved SOAP client promise
      const applications = results[1];  // This is the resolved Application objects
      this.lastChecked = new Date();

      // Iterate through applications and update if necessary
      applications.forEach((application) => {
        if (_.isEmpty(application.buc) || _.isEmpty(application.adn)) {
          application.last_checked = this.lastChecked;
          application.valid_reason = 'BUC/ADN not set';
          application.save();
        } else {
          // bucVal is the operation defined in the WSDL
          client.bucVal({BUC: application.buc, ADN: application.adn})
            // This won't work, but this is what I want...
            .then((validationResult, application) => {
              // Need to update application with returned data
              application.last_checked = this.lastChecked;
              application.valid_reason = validationResult.invalidMsg;
              application.isValid = validationResult.isValid !== "FALSE";
              application.save();
            })
            .catch((error) => {
              console.log(error);
            });
        }
      });
    })
    .catch((error) => {
      console.log(error);
    });
};



via spdaly

No comments:

Post a Comment