简体   繁体   中英

Nodejs Promise for custom api

I am new to nodejs and using promise and actually this is my first real app with nodejs .

So i have been reading all day and i am a bit confused.

So this is my module :

function User() {
    var self   = this;
    self.users = {};

    self.start = function (user, botId) {
        return new Promise(function () {
           return get(user).then(function (data) {
                debug(data);
                if (data.botId.indexOf(botId) === false) {
                    return Repo.UserBotModel.addUser(user.id, botId).then(function () {
                        data.botId.push(botId);
                        return data;
                    });
                } else
                    return data;
            });
        });
    };

    self.getDisplayName = function (user) {
        if (user.real_name)
            return user.real_name;
        if (user.last_name)
            return user.firstname + ' ' + user.last_name;
        return user.first_name;
    };
    /**
     * check if user exist in our database/memory cache and return it,
     * otherwise insert in the database and cache it in memory and the return it
     * @param user
     */
    function get(user) {

        return new Promise(function () {

            //check if user is loaded in our memory cache
            if (self.users.hasOwnProperty(user.id))
                return self.users[user.id];
            else {
                //get from database if exist
                return Repo.UserModel.get(user.id).then(function (rows) {
                    if (rows && rows.length) {
                        //user exist cache it and resolve
                        var data = rows[0];
                        if (data.botId && data.botId.length)
                            data.botId = data.botId.split(',');
                        else
                            data.botId = [];

                        self.users[user.id] = data;
                        //------------------------------ code execution reaches here
                        return data;
                    }
                    else {
                        //user dose not exist lets insert it
                        return Repo.UserModel.insert(user).then(function (result) {
                            return get(user);
                        });
                    }
                });
            }
        });
    }
}

I call the start method witch calls the private get method the call reaches return data; (marked with comment) but then function dose not gets executed in the start method ???

So what am i doing wrong?

UPDATE : Sorry I forgot to mention that I am using bluebird and not the native promise if that makes a difference?

You cannot return from the Promise constructor - you have to call resolve (expected to happen asynchronously). You're not supposed to use the Promise constructor at all here. You can just omit it, and it should work.

  • The methods from your Repo.UserModel already return promises, so you do not have to create new ones using new Promise .
  • You can read the values inside those promises using then .
  • then also provides a way to transform promises. If you return a value in a function passed to then , then will return a new promise that wraps the value you returned. If this value is a promise, it will be awaited.
  • To convert a value to a promise, you can use Promise.resolve .

Knowing that, you can simplify get like so:

function get(user) {
    if (...) {
        return Promise.resolve(...)
    } else {
        return Repo.UserModel.get(...).then(function(rows) {
            ...
            return ...
        })
    }
}

This version of get will always return a promise that you can use like so:

get(...).then(function(resultOfGet) {
    // process resultOfGet
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM