0

I am unable to pass the value outside the scope once i resolved the promise. Please check my code here.

var FullName;
async.series([
  function(callback) {
    var name = element(by.css('.xyz')).getText().then(function(text) {
      console.log("print name" + text);
      FullName = text;
      console.log("Able to print successfully" + FullName);
    });
    console.log("Unable to print the name outside" + FullName);
    callback();
  },
  function(callback) {
    //I want to retrieve the FullName value to this function. 
    //but unable to bring the value to this function
    console.log("Unable to print the name on the second function too" + FullName)
    callback();
  }

], function(err) {
  done();
})
James
  • 129
  • 2
  • 11
  • Possible duplicate: [How do I return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – jfriend00 Aug 25 '17 at 04:05
  • 3
    Mixing the `async` library and promises is generally a mess. If your underlying operations are already using promises (which they appear to be here), then just use promises for flow control too, not the async library. – jfriend00 Aug 25 '17 at 04:07

1 Answers1

0

I've added comments to the first part of your code to explain the problem

var FullName;
async.series([
  function(callback) {
    var name = element(by.css('.xyz')).getText().then(function(text) {
      console.log("print name" + text);
      FullName = text;
      console.log("Able to print successfully" + FullName);
    });
    // here, the .then callback hasn't been invoked yet, so FullName is not yet changed
    console.log("Unable to print the name outside" + FullName);
    // and, you're calling callback() before the .then callback is invoked, so, in the next code, FullName is not changed either
    callback();
  },

You could rewrite it as this

var FullName;
async.series([
  function(callback) {
    var name = element(by.css('.xyz')).getText().then(function(text) {
      console.log("print name" + text);
      FullName = text;
      console.log("Able to print successfully" + FullName);
      callback(); // callback once all asynchronous ops are done
    });
  },
  function(callback) {
    console.log("Now able to print the name on the second function " + FullName)
    callback();
  }

], function(err) {
  done();
})

or, simply, without async.js, because Promises + async.js is never really a good combination anyway, your code is equivalent to

element(by.css('.xyz')).getText()
.then(function(FullName) {
    // do wahtever you need to with FullName in here, note it's NOT global
});
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87