[英]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. 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. Below is the code:下面是代码:
node_modules/<my package>/index.js 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 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
})()
The log gets filled up with "Authenticated!"日志充满了“已验证!” and the code never makes it to
console.log("App initialized!")
.并且代码永远不会到达
console.log("App initialized!")
。 I've seen this answer but it does not help me because I know this
is referring correctly to the object.我已经看到了这个答案,但它对我没有帮助,因为我知道
this
正确地指的是 object。
Replacing resolve(this)
with resolve()
stops this, but await new MyAPI()
resolves to undefined
and I cannot later run app.getSomething()
.用 resolve() 替换
resolve(this)
resolve()
停止这个,但是await new MyAPI()
解析为undefined
并且我以后不能运行app.getSomething()
。
In a non-Thenable class (eg new MyClass()
), it resolves to the object itself, so further operations can be done on it, so why can't await new MyAPI()
also resolve to the object itself like a constructor should?在非 Thenable class (例如
new MyClass()
)中,它解析为 object 本身,因此可以对其进行进一步操作,所以为什么不能await new MyAPI()
也解析为 ZA8CFDE6331BD59EB2AC96F8 本身,如构造函数?
Just don't do that.只是不要那样做。 Instead of making your objects thenable, give them an
init
method that simply returns a promise.与其让你的对象成为 thenable,不如给它们一个简单地返回 promise 的
init
方法。 Then use them as然后将它们用作
const app = new MyAPI(config.auth.token);
await app.init();
console.log("App initialized!");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.