2016-06-15 44 views
0

我正在试图在nodejs中创建一个模块,所以我创建了一个名为Client的对象,该对象具有构造函数和一些方法。Nodejs只有在对象初始化后才执行对象的方法

问题是构造函数运行异步请求(使用请求),并且方法需要构造中的东西才能被正确调用。

我如何使构造器同步?

function Client(id){ 
    var token; 
    o = { 
     method: 'POST', 
     url: url + '/getToken', 
     headers: headers, 
     json: true, 
     body: id } 

    request(o).then(function(body) { 
     token = JSON.parse(body).token 
    }) 

    function getValue(){ 
    return new Promise(function(ff, rj) { 
     o = { 
      method: 'GET', 
      url: url + '?token=' + token, 
      headers: headers 
     } 
     request(o).then(function(body) { 
      ff(JSON.parse(body).value) 
     }) 
    }) 
    } 

    return{ 
    getValue 
    } 
} 

我想要做这样的事情

var client = Client(id) 
client.getValue().then(console.log) 

,但是由于要求异步的,当时的GetValue返回一个错误(令牌不具有价值尚) 我怎样才能做到这一点?谢谢

回答

2

您应该将token作为依赖关系,并分别执行async,也许在某种工厂函数中。

function Client(token) { 
    this.getValue = function() { 
    return request({ 
     method: 'GET', 
     url: url + '?token=' + token, 
     headers: headers 
    }).then(function (body) { 
     // Notice that you can return a synchronous value instead of a 
     // promise here. It will be wrapped in a promise and the next 
     // .then call will receive this returned value. 
     return JSON.parse(body).value; 
    }); 
    } 
} 

function clientFactory (id) { 
    return request({ 
    method: 'POST', 
    url: url + '/getToken', 
    headers: headers, 
    json: true, 
    body: id 
    }).then(function (body) { 
    var token = JSON.parse(body).token; 
    return new Client(token); 
    }); 
} 

或者,如果你想使用ES6类&箭头功能:

class Client { 
    constructor (token) { 
    this.token = token; 
    } 
    getValue() { 
    return request({ 
     method: 'GET', 
     url: `${url}?token=${this.token}`, 
     headers: headers 
    }).then((body) => JSON.parse(body).value); 
    } 
} 

function clientFactory (id) { 
    return request({ 
    method: 'POST', 
    url: `${url}/getToken`, 
    headers: headers, 
    json: true, 
    body: id 
    }).then((body) => new Client(JSON.parse(body).token)); 
} 

的ES6类的例子实际上是更好,因为你不重新创建getValue方法的每一个新实例Client。为了让第一个例子是高性能的ES6例子,你不得不做这样的:

function Client(token) { 
    this.token = token; 
} 
Client.prototype.getValue = function() { 
    return request({ 
    method: 'GET', 
    url: url + '?token=' + this.token, 
    headers: headers 
    }).then(function (body) { 
    return JSON.parse(body).value; 
    }); 
}; 

现在,你应该能够做这样的事情:

var client = clientFactory(id).then(function (client) { 
    client.getValue().then(console.log); 
});