我正在開發一個 NodeJS 包,其中包含一個應該回傳的 Thenable 類(請參閱Thenable 物件)this(已初始化的物件本身),但它回傳的是一個新的、未初始化的物件,并且它陷入了一個永無止境的回圈。下面是代碼:
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正確地參考了該物件。
替換resolve(this)為resolve()停止此操作,但await new MyAPI()決議為undefined并且我以后無法運行app.getSomething().
在非Thenable類(例如new MyClass())中,它決議為物件本身,因此可以對其進行進一步的操作,那么為什么不能await new MyAPI()像建構式那樣也決議為物件本身呢?
uj5u.com熱心網友回復:
只是不要那樣做。與其讓你的物件成為 thenable,不如給他們一個init簡單地回傳一個Promise 的方法。然后將它們用作
const app = new MyAPI(config.auth.token);
await app.init();
console.log("App initialized!");
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/408216.html
標籤:
