[英]How do I properly return 'this' in Thenable objects?
I am developing a NodeJS package that contains a Thenable class (see Thenable objects ) that is supposed to return this
(the initialized object itself), but instead it is returning a new, uninitialized object and it is stuck in a neverending loop. 下面是代码:
node_modules/<我的包>/index.js
const axios = require('axios');
const config = require('./config.json');
class MyAPI {
#token = "";
constructor(username, password) {
this.#token = token;
}
then(resolve, reject) {
const options = {
url: "/api/authenticate",
baseURL: "https://myapi.com/",
method: 'post',
maxRedirects: 0,
data: {
token: this.#token
},
transformRequest: this.#transformRequest('urlencoded'),
transformResponse: this.#transformResponse
};
axios.request(options).then((res) => {
if (res.data.authenticated === true) {
console.log("Authenticated!");
resolve(this); // <-- should return the initialized object, but instead returns a new uninitialized object
} else {
reject(new Error('Invalid credentials'));
}
});
}
#transformRequest(type) {
if (type === 'urlencoded') {
return function(data) {
return (new URLSearchParams(data)).toString();
}
} else if (type === 'json') {
return function(data) {
return JSON.stringify(data);
}
}
}
#transformResponse(data) {
return JSON.parse(data);
}
getSomething() {
// Gets something from remote API
return response;
}
}
module.exports.MyAPI = MyAPI;
index.js
const { MyAPI } = require('<my package>');
(async function(){
try {
const app = await new MyAPI(config.auth.token);
console.log("App initialized!"); // Code never reaches this command
console.log(app.getSomething());
} catch (e) {...} // Handle the error
})()
日志充满了“已验证!” 并且代码永远不会到达console.log("App initialized!")
。 我已经看到了这个答案,但它对我没有帮助,因为我知道this
正确地指的是 object。
用 resolve() 替换resolve(this)
resolve()
停止这个,但是await new MyAPI()
解析为undefined
并且我以后不能运行app.getSomething()
。
在非 Thenable class (例如new MyClass()
)中,它解析为 object 本身,因此可以对其进行进一步操作,所以为什么不能await new MyAPI()
也解析为 ZA8CFDE6331BD59EB2AC96F8 本身,如构造函数?
只是不要那样做。 与其让你的对象成为 thenable,不如给它们一个简单地返回 promise 的init
方法。 然后将它们用作
const app = new MyAPI(config.auth.token);
await app.init();
console.log("App initialized!");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.