Monday 8 May 2017

NodeJS - Return value of a promise inside a promise (Bluebird)

Hey guys I'm using Bluebird, Express-Validator, and Sequelize in this particular problem.

My current code looks like this

    req.checkBody("firstname").isLength({ min: 0, max: 35 });
    req.checkBody("lastname").isLength({ min: 0, max: 35 });
    req.checkBody("username").isLength({ min: 0, max: 35 });
    req.checkBody("email").isLength({ min: 0, max: 255 }).isEmail();
    req.asyncValidationErrors().then(() => {
        let request: CreateUserRequest = {
            firstname: req.body.firstname,
            lastname: req.body.lastname,
            username: req.body.username,
            email: req.body.email
        };

        return request;
    }).then((request: CreateUserRequest) => {
         //POINT A - Returns a Promise which resolves into UserInstance object
         return Database.userSchema.create({
            firstname: request.firstname,
            lastname: request.lastname,
            username: request.username,
            permissions: {},
            email: request.email,
            signupdate: new Date(),
            settings: {},
            setup: false,
            password: ""
        });
    }).then((createdUser) => {
        //POINT B - Would like createdUser to be a UserInstance object
          //instead of Promise<UserInstance>
    }).catch((err) => {
        console.log(err);
        res.status(400).end();
    });

My problem is, in the last then I would like to be able to use the actual instance value that is returned when the Database.userSchema.create promise is fulfilled. But if I return that object my last then with the parameter (createdUser) actually gets the promise instead of the value. How should I break this chain and get createdUser to get the value of the promise after it fulfills?



via Duxducis

No comments:

Post a Comment