0

In my code, I use a function in another, where the inner one returns a value. Like that:

function first(){
    /*do stuff*/
    return stuff;
}
function second(){
    var result = first;
}

But my problem is the second function doesn't wait the first one and thus, I get a undefined return.

How can I force a function to wait another to get a synchronous function ?

phenric
  • 307
  • 1
  • 8
  • 15
  • If your /*do stuff*/ is asynchronous (like a web call, etc.), then 'return stuff;' does not do what you think it does. It will only return the value of 'stuff' from before the async call. So, as Terry said, a Promise might be the way to go. You could also set up a listener for 'do stuff' to call on completion. This would then have the result of 'do stuff', which you can then process. – Jim Feb 23 '18 at 14:11

1 Answers1

4

I'd use a promise for this, return a promise from the first..

As in:

function first(){
  /*do stuff*/
  return Promise.resolve(stuff);
}

first().then((stuff) => {
    second(stuff);
});

A slightly more concrete example, let's do some asynch. stuff:

function first(){
    return new Promise((resolve) => {
        setTimeout(resolve, 100, 'stuff');
    });
}

function second(stuff){
    console.log('second: ', stuff);
}

first().then((stuff) => {
    second(stuff);
});

In newer versions of Node.js you can also do:

var testIt = async function()
{
    var result = await first();
    second(result);
}

testIt();

This is a little syntactical sugar that makes the code easier to understand.

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40