【问题标题】:Node.JS return out of callbackNode.JS 从回调中返回
【发布时间】:2015-05-19 16:34:09
【问题描述】:

我正在使用这个插件管理器https://github.com/c9/architect 并创建一个节点模块。我遇到的问题是我想将我的节点模块中的 api 公开给主机应用程序。问题是插件管理器使用回调来表示所有插件都已注册。

示例: 在我的主应用程序中,我需要我正在创建的 api 模块

var api = require('apiModule')

在我的 node_modules 目录中

module.exports = (function apiModule(){

    architect.createApp(config, function(err, app){
        if(err) throw err;

        return app

    });

})();

这显然不起作用,但表明我正在尝试将app 的值返回给主应用程序。

如何将app 的值返回给api 变量?

【问题讨论】:

    标签: javascript node.js callback return-value node-modules


    【解决方案1】:

    您可以将回调传递给您的模块:

    module.exports = function(callback){
    
        architect.createApp(config, function(err, app){
            if(err) throw err;
    
            return callback(app); //you should check if callback is a function to prevent error
    
        });
    
    });
    
    var api = require('apiModule');
    api(function(app) {
        console.log(app); //you access your app
    
    })
    

    【讨论】:

    • 是的,我想到了,但你必须记住,我将把这个模块提供给其他人。我不能让他们在我的回调中包装他们的整个应用程序。我需要他们能够require() 并能够使用它。即使他们必须执行第二步,也许共享变量将变得可用或其他什么。
    【解决方案2】:

    你不是在传递一个回调,而是创建一个。 你的函数也不应该自己执行。

    你的代码应该是:

    var architect = require('architect');
    module.exports = function apiModule(config, callback){
    
        architect.createApp(config, callback);
    
    });
    
    //otherModule
    var apiModule = require('apiModule');
    var config = require('config');
    apiModule(config, function(err, app){
        if(err) throw err;
    
        // do something with app
    });
    

    如果您正在寻找更符合您习惯的 API。 我建议你试试bluebird

    var architect = require('architect');
    var Promise = require('bluebird');
    var createApp = Promise.promisify(architect.createApp);
    module.exports = function apiModule(config) {
        return createApp(config);
    }
    
    // Then in your other module
    var apiModule = require('apiModule');
    apiModule()
        .then(function(result) {})
        .catch(function(error) {})
    

    我希望能解决这个问题:)

    【讨论】:

    • 第一个模块中的函数会在你require('apiModule') 时立即执行,失败导致callback 不会被定义。您必须删除 ()
    • 您很快就减去了答案,但懒得提供解决方案。举止优雅。
    • 在上面的答案中查看我的 cmets。我不能要求下载我的模块的用户用我的回调函数包装他们的应用程序
    • 好的,这不是它在 node 的异步世界中的工作方式。如果您的用户正在使用您的 lib 并且它正在执行异步函数,他们仍然必须传入回调,否则他们将永远不会得到结果。
    • 我对此进行了深入研究,并意识到这与标准回调没有什么不同。我需要的解决方案是能够将此异步模块加载器转换为同步过程或尽可能接近。我不能要求用户在回调函数中编写所有代码。
    猜你喜欢
    • 2014-03-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 2017-01-27
    • 2018-08-15
    • 2021-08-17
    • 1970-01-01
    相关资源
    最近更新 更多