(Node js) Prevent lost session context node-continuation-local-storage in Promise


This topic maybe too old but it will help you understand more about scope and lifetime of variable in node js: http://blog.mixu.net/2011/02/03/javascript-node-js-and-for-loops/

And in the previous topic: I have been mention about “node-continuation-local-storage” https://quangphamsoft.wordpress.com/2017/07/03/node-js-preserving-data-across-async-callbacks-with-continuation-local-storage-and-mongodb-client/

When we start session for each request with:


 session.run(() => {
	session.set(UtilHelper.USER_ID, user._id);
	session.set(UtilHelper.USER, user);
	next();
});

 

Sometime we need to define some Promise to handler another purpose like this:

    public static getSession(key: string): string {
        let session = require('continuation-local-storage').getNamespace(this.SESSION_NAMESPACE);
        if (session != undefined) {
            return session.get(key);
        }
        return '';
    }

 

So if you got problem with lost context of session by function get session, it’s mean when you use “session.get(key)” it will return empty value, to resolved your problem first of all you put callback to function:

public testPromise(): Promise {
    let promise = new Promise((resolve, reject) => {
        ((index) => {
            setTimeout(() => {
                let data = UtilHelper.getSession(UtilHelper.USER);
                resolve();
            }, 0);
        })();

    });
    return promise;
}
 

And your implement can get session after callback:

 let promise: Promise = RestaurantManager.insert(restaurant);

        promise.then((httpStatus: HttpStatus<Restaurant>) => {
            ...
            let data = UtilHelper.getSession(UtilHelper.USER); // get session here
            let user: User = deserialize<User>(User, data);
            if (user != null) {
                user.access.push(access);
                user._id = UtilHelper.getObjectId(user._id);
                UserManager.update({ _id: UtilHelper.getObjectId(user._id) }, user).then((response) => {
                 ...
                }).catch((err: ErrorHandler) => {
                   ..
                });
            }
            else {
                ..
            }

        })
            .catch((err: ErrorHandler) => {
                ...
            });

 

Hope help you something!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s