从嵌套回调函数内部返回方法

时间:2019-05-20 11:49:17

标签: javascript node.js callback

除了调用函数之外,我还有一个包含查询函数和组合回调的函数:

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

    //...do some stuff with response
}

哪个会导致:

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!";
}

我考虑过两种处理方法。第一个也是最明显的一点就是以某种方式允许“双倍回报”。我的意思是说,在回调函数中返回值将返回外壳(需要一个更好的词)功能。

第二种方式就是这样:

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!";
    }
}

这种方法不仅笨拙,还需要绝对确保回调函数已完成执行(在此示例中,它将没有)。通常,我会将我的代码放入回调块中以确保其已执行,但是当尝试像这样返回时,显然不能。

对于刚接触节点的人是否有一个优雅的解决方案?

0 个答案:

没有答案
相关问题