【问题标题】:How to get back from inside function syncronized in node.js?如何从 node.js 中同步的内部函数返回?
【发布时间】:2013-11-20 05:29:12
【问题描述】:
function squre(val) {
    main.add(val,function(result){
        console.log("squre = " + result); //returns 100 (2nd line of output)
        return result;
    });
}

console.log(squre(10));  // returns null (1st line of output)

我需要 100 作为两行的输出。

【问题讨论】:

  • 对不起它已经是方形的功能(我刚刚在我的问题中编辑)

标签: node.js function asynchronous callback synchronization


【解决方案1】:

这取决于main.add() 的性质。但是,通过使用回调,它很可能是异步的。如果是这种情况,那么return 根本无法正常工作,因为“异步”意味着代码不会等待result 可用。

您应该通读“How to return the response from an AJAX call?”。虽然它以 Ajax 为例,但它对异步编程和控制流的可用选项进行了非常透彻的解释。

您需要定义squre() 来接受它自己的回调并调整调用代码以提供一个:

function squre(val, callback) {
    main.add(val, function (result) {
        console.log("squre = " + result);
        callback(result);
    });
});

squre(10, function (result) {
    console.log(result);
});

不过,如果 main.add() 实际上是同步的,您可能需要移动 return 语句。他们只能应用于他们直接所在的function,这将是匿名的function,而不是spure()

function squre(val) {
    var answer;
    main.add(val, function (result) {
        console.log("squre = " + result);
        answer = result;
    });
    return answer;
}

【讨论】:

    【解决方案2】:

    您不能,因为您有异步函数main.add(),它将在事件循环的当前刻度之外执行(有关更多信息,请参阅this article)。 squre(10) 函数调用的值为undefined,因为此函数不会同步返回任何内容。看这个sn-p的代码:

    function squre(val) {
        main.add(val,function(result){
            console.log("squre = " + result);
            return result;
        });
    
        return true; // Here is the value really returned by 'squre'
    }
    
    console.log(source(10)) // will output 'true'
    

    The Art of Node 了解有关回调的更多信息。

    要从异步函数中取回数据,您需要给它一个回调:

    function squre(val, callback) {
      main.add(val, function(res) {
        // do something
        callback(null, res) // send back data to the original callback, reporting no error
    }
    
    source(10, function (res) { // define the callback here
      console.log(res);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 2020-09-12
      • 1970-01-01
      • 2014-05-27
      • 2020-09-25
      相关资源
      最近更新 更多