NodeJS类方法asynchronous返回

我目前正在使用login方法在JavaScript中编写一个类。

const EventEmitter = require('events'); const util = require('util'); const Settings = require('./config'); const config = new Settings(); const http = require('request'); class Client extends EventEmitter { constructor(username, password) { super(); this.username = username; this.password = password; } get login() { return this.login(); } login() { http.post({ url: config.host + "v" + config.version + "/method/account.signIn.inc.php", body: "username="+ this.username + "&password=" + this.password + "&clientid=" + config.clientid }, function(error, response, body){ return body; }); } } module.exports = Client; 

我正在使用请求模块发出HTTP请求,但请求正在使用asynchronous调用,并且在调用console.log(client.login());时我总是处于undefined状态console.log(client.login()); 从另一个文件。 我已经看到许多针对具有callback的asynchronous调用的解决scheme,但是我似乎无法用类内的callback或承诺来解决这个问题。

有很多方法可以做到这一点 – callback,事件,承诺。 大多数人往往喜欢有承诺的解决scheme,这是一个很好的用例。 有了承诺,你可以做这样的事情:

 login() { return new Promise((resolve, reject) => { http.post({ url: config.host + "v" + config.version + "/method/account.signIn.inc.php", body: "username="+ this.username + "&password=" + this.password + "&clientid=" + config.clientid }, function(error, response, body){ if (error) return reject(error) resolve(body); }); }) } 

那么你可以打电话给它:

 let client = new Client(username, password) client.login() .then(result => { // result available here }) .catch(err => { // an error }) 

话虽如此,它也看起来像你正在定义的类作为EventEmitter的子类,这表明你想使用事件。 你也可以使用这个来表示login类似的东西:

 login() { http.post({ url: config.host + "v" + config.version + "/method/account.signIn.inc.php", body: "username="+ this.username + "&password=" + this.password + "&clientid=" + config.clientid }, (error, response, body) => { this.emit("loggedIn", body) }); } 

然后在调用login()之后等待事件

 let client = new Client(username, password) client.on("loggedin", (returnVal) => console.log("returned", returnVal)) client.login() 

当然,你会想要一些错误检查,你可能想在你的实例上login后设置一个标志,所以你可以在初始login后检查。

我认为login()应该返回一个promise:

 login() { return new Promise((resolve, reject) => { http.post({ url: config.host + "v" + config.version + "/method/account.signIn.inc.php", body: "username=" + this.username + "&password=" + this.password + "&clientid=" + config.clientid }, function(error, response, body) { if (error) reject(error); else resolve(body); }); }); } 

当调用它时:

 client.login().then(result => console.log(result)); 

我有点新的NodeJS和asynchronous编程,但我认为这是做到这一点。