yortus / asyncawait

Callback heaven for Node.js with async/await
MIT License
1.91k stars 77 forks source link

this context not preserved #49

Closed bvjebin closed 7 years ago

bvjebin commented 7 years ago

The following piece of code is what I am trying.

"use strict";
const Async = require("asyncawait/async");
const Await = require("asyncawait/await");
const State = require("./../models/state.js");
const bot = {
    setFn(what) {
        console.log(what);
    },
    receive: Async((obj) => {
        console.log(this, obj);
        this.setFn(obj);
        let state = Await(State.find("zzzz")); //returns promise
        return state;
    })
};
bot.receive({a: 1});

This snippet when run throws the following exception:

Unhandled rejection TypeError: this.setFn is not a function
    at Object.bot.receive (tests/asyncawait.js:11:14)
    at tryBlock (node_modules/asyncawait/src/async/fiberManager.js:39:33)
    at runInFiber (node_modules/asyncawait/src/async/fiberManager.js:26:9)

What am I doing wrong? When I printed this it just printed empty object. Documentation mentions that the this context is preserved. But seems like it is lost.

Can anyone help on this?

bvjebin commented 7 years ago

Figured it out myself. It is the context binding issue. When I changed the code as given below, things started working.

const bot = {
    setFn(what) {
        console.log(what);
    },
    receive(obj) {
        return Async((obj) => {
            console.log(this, obj);
            this.setFn(obj);
            return Await(State.find("zzzz"));
        })(obj);
    }
};
bot.receive({a: 1});

Good work BTW.