anonymous
anonymous

Reputation: 101

how to access promoise variable value outside

async selectAvailableRoute(routeCount: number) : Promise<any>{
var newRouteNum='';
for (let i = 1; i <= routeCount; i++) {

  this.availableRoute(i).click();
  this.availableRoute(i).getText().then(function (createdRouteNum) {
    Utils.logger('number'+ createdRouteNum);
    newRouteNum= createdRouteNum;

   });
return newRouteNum;

}

}

value of newRouteNum is coming as undefined. Can someone help to get the proper value

Upvotes: 1

Views: 29

Answers (1)

Kent Shikama
Kent Shikama

Reputation: 4060

Don't think about taking a value outside of a Promise as you could be executing that outside code before the Promise gets resolved: see the following SO answer but in short, get used to the asynchronous nature of Javascript. Instead just pass the Promise itself around and continue to use the resolved value.

async selectAvailableRoute(routeCount: number) : Promise<any>{
  // do whatever
  return this.availableRoute(i).getText().then(function (createdRouteNum) {
    // do whatever
    return createdRouteNum;
  });
}

// Just keep reusing the Promise as follows
var promise = selectAvailableRoute(...)
promise.then(function(createdRouteNum) {
   // do whatever
});

You can use the async/await syntax to alleviate the nesting but it doesn't change the nature of the problem.

Upvotes: 1

Related Questions