【问题标题】:Set object property after asynchronous call in node在节点中异步调用后设置对象属性
【发布时间】:2015-06-04 12:15:06
【问题描述】:

如何创建一个 nodejs 模块,它将一个 post 请求发送到一个 url 并返回一个对象,该对象的 data 属性设置为从 post 请求返回的数据?

var client = require('node-rest-client').Client();

module.exports = (function(){
    var instance;

    function createInstance(){
        client.post(url,function(data){
            //set instance.data = data OR
            // return function that lets me access a private property 'data' set to data returned in this callback
        });
    }

    return {
        Cloud : function(){
            if(!instance){
                instance = createInstance();
            }

            return instance;
        }
    }
})

编辑:

基本上当我调用上述模块并执行云函数时:

var cloud = require('module').Cloud(); 控制台.log(cloud.data); //应该给我从发布请求中收到的数据。 //我也想使用模块模式来做到这一点,在模块内发布请求。

【问题讨论】:

  • 你的意思是你想通过 HTTP POST 获取一些数据到一个特定的 url?什么样的返回数据? JSON、XML 等?
  • 您不能直接从模块函数返回异步操作的结果。相反,您可以让调用者传入一个回调,该回调将使用异步操作的结果进行调用,或者您可以返回一个 Promise,该承诺将在异步操作完成时使用结果解析。
  • 如前所述,你想要的都是不可能的。你必须用另一种方式(回调或承诺)。
  • 如果我将对象发送到函数会怎样:所以云:函数(obj),并且回调设置 obj 的属性。这有什么问题吗?

标签: node.js callback singleton node-modules


【解决方案1】:

你可以使用一个承诺,例如:

function postReq() {
    return new Promise(function(resolve, reject) {
       client.post(url, function(data) {
           resolve(data);
       })
    });
}

postReq()
.then(function(data) {
  // Do whatever you want with the data returned from client.post
  console.log(data);  
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2021-08-25
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    相关资源
    最近更新 更多