0

I have a javaScript method that returns a promise of reading data from an Excel sheet and return it in an array.

/* Get Column Data and return */
this.getColumnData = function(FileName,SheetName,ColumnName)
{
    var ColumnDataList = new Array();
    var workbook = new Excel.Workbook(); 
    return workbook.xlsx.readFile(FileName).then(function() {
            var worksheet = workbook.getWorksheet(SheetName);
            for(var v=2;v<=worksheet.actualRowCount;v++)
            {
                ColumnDataList.push(worksheet.getCell(ColumnName+v).value);
            }
          return ColumnDataList;
        });     
};

Now while implementing the JS callback, I'm trying to assign the returned array in a variable and use it further, something like this:

var tmp = [];
    it('Search TC#1 - ISBN ', function(){ 
        xlReader.getColumnData('Test_Data.xlsx','Sheet1','A').then(function(dataList) {
            tmp=dataList;
            console.log('Inner Data : '+tmp);
            });
        console.log('Outer Data : '+tmp);
        });

When I assign the returned value in a var tmp this tmp value can be accessed from inside the promise callback body but not from the outside. so the result that it prints is this:

Outer Data :

Inner Data : 9781405342704,9780241186091,9780241340189

As you can see that it returns nothing when called from outside of JS promise callback whereas I want to access the tmp variable data from the outside of promise callback body.

Pankaj Dubey
  • 279
  • 2
  • 18

1 Answers1

1

The tmp can be accessed outside because it's within the lexical scope, but since the promise runs asynchronously, at the time the interpreter reaches

console.log('Outer Data : '+tmp);

, tmp has not been populated yet.

Put all of your asynchronous logic inside the .then, or use await instead.

it('Search TC#1 - ISBN ',  async function() {
  const dataList = await xlReader.getColumnData('Test_Data.xlsx','Sheet1','A');
  // do stuff with dataList
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you very much @CertainPerformance for explaining the reason of the error. I'm trying to implement the solution given by you but having some issues to do it as async and await keywords are not recognized in my script. I'll post the update here. – Pankaj Dubey Mar 21 '18 at 05:42