0

I have a function that contains a query function and combined callback in addition to its calling function:

function MyCallingFunction()
{
    var response = MyFunction();

    //...do some stuff with response
}

Which leads into:

function MyFunction()
{
    //does some stuff
    ReturnRows(query, connection, function(result)
    {   
        //... Omitted error handling

        if(result == null) //this is a pseudocode for clarity
        {
            return "There was an error!";
        }

    });

    return "There were no errors!";
}

There are two ways that I've considered approaching. The first, and most obvious, is somehow allowing a "double return". By which I mean a return in the callback returns the housing (for want of a better word) function.

The second way involves something just like that:

function MyFunction()
{
    //does some stuff
    var returned = ReturnRows(query, connection, function(result)
    {   
        //... Omitted error handling

        if(result == null) //this is a pseudocode for clarity
        {
            return "Error";
        }
        else
        {
            return "Success";
        }
    });

    if(returned.includes("Error"))
    {
        return "There was an error!";
    }
    else
    {
        return "There were no errors!";
    }
}

Not only is this approach quite clumsy, I need to be absolutely sure that the callback function has finished executing (in this example, it won't have). Ordinarily I would put my code within the callback block to make sure it's executed, but when trying to return like this I obviously can't.

Is there an elegant solution for someone new to node?

James
  • 356
  • 2
  • 13
  • I'd transform it into a Promise-based function (rather than callback-based), call `.then` on the Promise to examine what it resolves to, then return the whole Promise chain to the caller of `MyFunction` – CertainPerformance May 20 '19 at 11:51
  • any thing you will return from callback handler function will get returned to calling function which is calling handler defined by you i.e. some place in `ReturnRows` function. Batter you use callback as argument to `MyCallingFunction`. – JackOfAshes - Mohit Gawande May 20 '19 at 11:57
  • @CertainPerformance That was an excellent source thanks. I ended up using Promises as you detail in your comment. – James May 20 '19 at 15:16

0 Answers0