0

I need to access a variable from inside a then block that is declared in the outer function, but for some reason some of them show up as undefined. Are there specific names that are accessible within the scope of a then?

function foo(tableIDs, tableID, fieldID)
{
    var tables = new Array();
    var bar = new Array();
    var zim = new Array();
    var gir = new Object();

    zim.push(fieldID);
    gir.id = fieldID;

    otherFunction(tableID).then(function(response)
    {
         tables.push(response); // works fine
         bar.push(response); // bar is undefined
         zim.push(response); // zim is undefined
         gir.response = response; //gir is undefined
    });
}

Additionally while tableIDs is accessible inside the then statement, neither tableID nor fieldID are. For the time being I'm "solving" this by pushing fieldID into tables and accessing it that way before dealing with the response but that seems like a really ugly solution I would like to avoid. Seeing as the only difference between tables and bar is the name of the variable all names used in the example above are exactly what I used while working on this.

1 Answers1

0

Your code works perfectly. I've finished your implementation for testing purposes, and works fine. Check it:

function otherFunction(tableID){
  return new Promise(function(resolve,reject){
    resolve(tableID)
  })
}
  

function foo(tableIDs, tableID, fieldID){
    var tables = new Array();
    var bar = new Array();
    var zim = new Array();
    var gir = new Object();

    zim.push(fieldID);
    gir.id = fieldID;

    otherFunction(tableID).then(function(response){
         tables.push(response); 
         bar.push(response); 
         zim.push(response); 
         gir.response = response; 
         
         console.log('response:',response)
         console.log('tables:',tables)
         console.log('bar:',bar)
         console.log('zim:',zim)
         console.log('gir:',gir)
         console.log('tableIDs:',tableIDs)
         console.log('tableID:',tableID)
         console.log('fieldID:',fieldID)

    });
}

foo('test-tableIDs' , 'test-tableID', 'test-fieldID')

Your must have an error on passing arguments to foo(), or in your Promise function...

colxi
  • 7,640
  • 2
  • 45
  • 43