0

I am trying to update value of a variable inside the promise function. What am I doing wrong?

var data="valueoutside";

wb.xlsx.readFile(filePath).then(function(){

data="new value";
}
);

console.log(data); 
//shows 'valueoutside' as output and not 'new value'

3 Answers3

2

readFile is asynchronous, therefore console.log(data) is called before readFile has a chance to finish running and updating the value.

Change your code to this and it will work:

var data="valueoutside";

wb.xlsx.readFile(filePath).then(function() {
    data="new value";
    console.log(data); 
});

Another option would be to use a synchronous call:

var data="valueoutside";
var contents = wb.xlsx.readFileSync(filePath);

data="new value";

console.log(data); 
Daniel
  • 1,403
  • 1
  • 14
  • 30
0

Move your console.log(data) into the then handler, and you'll see the updated value.

var data="valueoutside";

wb.xlsx.readFile(filePath).then(function(){
    data="new value";
    console.log(data);
});

The function inside the then handler will execute once the promise resolves.

ajxs
  • 3,347
  • 2
  • 18
  • 33
0

ReadFile is asynchronous function. So you should write console.log in then function

var data="valueoutside";

wb.xlsx.readFile(filePath).then(function(){
   data="new value";
   console.log(data);
});