Javascript Class, this is undefined when returning Promise [duplicate]

社会主义新天地 提交于 2020-01-06 06:51:23

问题


I have a typescript app that it is losing 'this' context inside a class.

This class is responsible to setup new Express server instance.

I've setup a mock of the code to explain where I'm losing 'this' context.

In this little example the result is allways as expected but we can see with node inspect that 'this' is undefined at the same point as my real app.

Why is 'this' undefined inside Server? How would you change the code to not loose 'this'?

I've tried multiple options, like fn.bind(this) but allways 'this' is undefined.

'use strict';

 class Server {
    constructor(options) {
        this.options = options;
        this.server_id = null;
    }

    init () {
        return new Promise((resolve, reject) => {
            debugger; // this: Server

            this.startServer()
                .then(_ => {

                    debugger; // this: undefined

                    this.server_id = `ID_${this.options.port}`;

                    resolve(this);

                }, error => reject(error));
        });
    }

    startServer () {
        return new Promise((resolve, reject) => {

            function cb() {
                debugger; // this: Server
                resolve()
            }

            debugger; // this: Server

            this.listen(this.options.port, this.options.host, cb.bind(this));
        })
    }

    listen(port, host, cb) {
        debugger;
        cb()
    }
}

module.exports = Server
const Server = require('./server')

let s1 = new Server({
    port: 1111,
    host: 'localhost'
});

let s2 = new Server({
    port: 2222,
    host: 'localhost'
});

s1.init().then(() => {
    console.log(`Server S1 Started on port:${s1.options.port} ${s1.server_id}`);
});

s2.init().then(() => {
    console.log(`Server S2 Started on port:${s2.options.port} ${s2.server_id}`);
});

Result to expect:

  • Server S1 Started on port:1111 ID_1111
  • Server S2 Started on port:2222 ID_2222

What is returning in the real app:

  • Server S1 Started on port:2222 ID_2222
  • Server S2 Started on port:2222 ID_2222

I cannot post images:

UPDATE

Both Chrome and Vscode lose 'this' context

Vscode debugger This undefined Chrome debugger This undefined

Code above is not the transpiled version of typescript app, it's a mock of the typescript app that is facing the same issue, issue that you can not reproduce with this code (f***g witchcraft) but, both in Chrome and Vscode, you can see how when startServer() gets resolved it lost 'this' context.

I will post the typescript App that allways facing the issue (lost the context of 'this' but worst, it mixed it up...)

Thanks for your responses, very appreciated.

来源:https://stackoverflow.com/questions/57649046/javascript-class-this-is-undefined-when-returning-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!