gpt4 book ai didi

javascript - NodeJS类方法异步返回

转载 作者:行者123 更新时间:2023-11-30 21:03:28 25 4
gpt4 key购买 nike

我目前正在用 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 请求,但请求使用的是异步调用,并且在调用 console.log(client.login()); 时我总是得到 undefined; 来自另一个文件。我见过许多针对带有回调的异步调用的解决方案,但我似乎无法通过类中的回调或 promise 来解决这个问题。

最佳答案

有很多方法可以做到这一点——回调、事件、 promise 。大多数人倾向于喜欢带有 promise 的解决方案,这对他们来说是一个很好的用例。有了 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) return reject(error)
resolve(body);
});
})
}

然后就可以调用了:

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

话虽如此,您似乎也在将该类定义为 EventEmitter 的子类,这表明您想要使用事件。您还可以使用它来指示登录,例如:

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()

当然,您需要进行一些错误检查,并且您可能希望在登录后在您的实例上设置一个标志,这样您就可以在初始登录后进行检查。

关于javascript - NodeJS类方法异步返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46876994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com