2016-06-15 1 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 
    } 
} 

私は私はそれを行うことができますどのように (トークンがまだ値を持っていない)のgetValueがエラーを返すとき、この

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

ような何かをしたいが、要求のための非同期の?ありがとうございました

答えて

2

依存関係としてtokenを取り込んで、何らかの種類の工場機能で別々に非同期を実行する必要があります。

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クラス&矢印機能を使用する場合:あなたはのすべての新しいインスタンスに対してgetValue方法を再作成していないので、

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クラスの例は、実際に優れているがClient

var client = clientFactory(id).then(function (client) { 
    client.getValue().then(console.log); 
}); 
:今、あなたはこのような何かを行うことができるはず

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; 
    }); 
}; 

:ES6の例のようにパフォーマンスの最初の例を作成するには、このようにそれを行う必要があるだろう

関連する問題