Thursday, 25 May 2017

Get a value from a promise chain in another class

I am trying to get the value of a queried ID called from another class however when I call the function it gives me a promise chain and not the value I am looking for.

The method in the class 'Helper' is below

function querySF() {
  var conn = new jsforce.Connection({
    // you can change loginUrl to connect to sandbox or prerelease env.
    loginUrl: 'https://www.salesforce.com'
  });

  return conn.login('someusername', 'password')
    .then(function(userInfo) {
      // Now you can get the access token and instance URL information.
      // Save them to establish connection next time.
      console.log(conn.accessToken);
      console.log(conn.instanceUrl);
      // logged in user property
      console.log("User ID: " + userInfo.id);
      console.log("Org ID: " + userInfo.organizationId);
      // ...

      return conn.query("SELECT Id FROM some place Where name = 'some name'")
    })
    .then(function(result) {
      console.log("total : " + result.totalSize);
      console.log("fetched : " + result.records.length);
      // is returning the id
      console.log(result.records[0].Id);
      return result.records[0].Id; // can see the id here when debugging
    })
    .catch(function(err) {
      console.error(err);
    });
}

I am exporting the module like this at the bottom of the class:

exports.querySF = querySF();

The other class called 'BookingEvent' calls the method like this: var theId = Helper.querySF; and it returns a promise, I have printed the promise to console console.log(Helper.querySF); to see the results:

Promise {
  _45: 0,
  _81: 1,
  _65: 'a0L46111001LyvsEAC', // This is the value I need
  _54: null,
  then: [Function],
  stream: [Function: createRequest] }

It was thought that I should be able to just use

helpers.querySF().then(function(value){ console.log(value); })

and be able to get the value however I am getting this error: Failed: helpers.querySF is not a function

I am quite new to promises and no one at my company can seem to solve the issue. I have research many different ways of resolving promises however they do not work and I also do not understand. Could someone help me resolve this promise so the id accessible whenever I call this method, which will be multiple times with different queries I will be sending in.



via Nicole Phillips

No comments:

Post a Comment