0

I've been reading up on Javascript closures and scope chains, but I haven't seen anything about maniuplating variables from within the scope chain. Here's a similar type of scenario I'm running into:

function first() {
  var a = [];
  a.push({firstFunction: 'yes'});

  doSomethingFunction(valueToPassIn, function() {
    a.push({secondFunction: 'yes'});

    doAnotherThingFunction(newValueToPassIn, function() {
      a.push({thirdFunction: 'yes'});
    })
  })

  console.log(a) //returns {firstFunction: 'yes'}
}

how can I get it to return {firstFunction: 'yes', secondFunction: 'yes', thirdFunction: 'yes'}

The code may have syntax errors, but it's the idea I'm trying to understand. I just wrote this code up on the fly so you guys could see a similar scenario as to what I'm trying to fix.

Thanks

Thomas
  • 2,356
  • 7
  • 23
  • 59
  • Are `doSomethingFunction` or `doAnotherThingFunction` asynchronous? If yes, then you can't do that. You'd have to do the logic inside the callback, or use promises. – elclanrs Aug 26 '14 at 18:15
  • yeah they're asynchronous – Thomas Aug 26 '14 at 18:17
  • Then this is a duplicate of the everyday async question. It has nothing to do with scope or closures, but with the order of execution of your code, because it is asynchronous. – elclanrs Aug 26 '14 at 18:19
  • Since they're Asynchronous you would have to put the `console.log()` into `doSomethingFunction`s `function` argument. – StackSlave Aug 26 '14 at 18:20

1 Answers1

1

I know this was answered in the comments but here is an example of using a callback.

function first(callback) {
  var a = [];
  a.push({firstFunction: 'yes'});

  doSomethingFunction(valueToPassIn, function() {
    a.push({secondFunction: 'yes'});

    doAnotherThingFunction(newValueToPassIn, function() {
      a.push({thirdFunction: 'yes'});
      callback(a);
    });

  });
}

first(function(a){ console.log(a); });

The only problem with this method is that it gets unruly when you have more than 3 or 4 nested callback functions. Promises are the way to handle it.

jsfiddle: http://jsfiddle.net/axqmvdxg/

Thad Blankenship
  • 2,242
  • 3
  • 16
  • 16