简体   繁体   English

如何在 Thenable 对象中正确返回“this”?

[英]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.

相关问题 如何创建一个解析为一个版本的javascript承诺? - How do I create a javascript promise which resolves to a thenable? 如何在Javascript中从包装的生成器函数返回? - How to return thenable from wrapped generator function in Javascript? 在对象数组中,如何在 React 中按属性返回所有对象? - In an array of Objects, how do I return all Objects by property in React? 如何正确地“赞”我的OpenGraph对象? - How do I get my OpenGraph objects to be “liked” properly? 如何在正确包含CDATA的同时正确地将XML转换为JS对象 - How do I properly convert XML to JS Objects while properly containing CDATA 我如何使用json函数返回对象 - how do i return objects using json function JS-Ooyala API:如何返回此对象的title属性? - JS - Ooyala API: How do I return this objects title property? 如何将任意JSON对象返回到jQuery自动完成列表? - How do I return arbitrary JSON objects to a jQuery Autocomplete list? 如何在 Javascript 中返回具有特定条件的对象数组? - How do I return an array of objects with certain conditions in Javascript? 如何在正确包含CDATA部分的同时正确地将XML转换为JS对象 - How do I properly convert XML to JS Objects while properly containing sections of CDATA
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM