0

my code looks something like this

var fs = require('fs');
var prom = require('prom');

fs.readFile('./bat.txt', function(err, data) {
  bar=JSON.parse(data);
  for(var x=0;x<Object.keys(bar).length;x++){
      prom.f(bar[x]).then(res => {console.log({bar[x]: res});
})}}

bar[x] is out of date by the time the callback is called and I didn't write prom.f() and can't change it. I have no idea how to solve this please help!!!

  • Does this answer your question? [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – user120242 Jun 25 '20 at 04:51
  • 1
    Not sure if this will fix your issue, but can you use `let x=0` instead of `var x=0`? What is the result? – Bronson Jun 25 '20 at 04:59
  • have you tried adding async to your callback function? – astroanu Jun 25 '20 at 14:39

1 Answers1

0

Because x will change immediately in each for loop you need to use closure(iife - immediately invoked function expression).

var fs = require('fs');
var prom = require('prom');

fs.readFile('./bat.txt', function(err, data) {

    bar = JSON.parse(data);

    // side note: don't do this 
    // for(var x=0;x<Object.keys(bar).length;x++){
    // if there was 1000 keys in bar
    // you would run Object.keys(bar) 1000 times
    // since the statement is evaluated in every loop

    var len = Object.keys(bar).length;
    for(var x = 0; x < len; x++){
        (function(xx){
            // xx will be same even in `then`
            prom.f(bar[xx]).then(res => {console.log({bar[xx]: res});

        })(x);  
    }
)}}
Molda
  • 5,619
  • 2
  • 23
  • 39