Monday, 22 May 2017

How can I create a promise helper function?

Im writing an api using node.js and rethinkdb.

In api's sometimes there are helper callback functions that take care of the big database query stuff and the api is then built using those helper functions so you dont repeat the same code over and over throughout the api. Like maybe theres a checkUserExists callback function that checks if the user exists before calling the createNewUser callback function.

I want to create those helper functions as promises to avoid callback hell right from the start:

I want to create a set of helper promises that I can use to build my api for example a checkUserExists("username") promise and a checkEmailExistsPromise("email@email.com") and a createNewUser("username","email") promise.

I would then be able to just chain them as I need and do things like:

checkUserExists.then(()=>{
return checkEmailExists();
}).then(()=>{
return createNewUser()
}).then((result)=>{
resolve(result);
})

My problem: Rethink db already uses promises so im not sure how to create my custom helper promise function out of it:

r.db("test").table("users").filter(function (user) {
    return user("name").match("(?i)^"+username+"$");
}).nth(0).default(null).run()

Im not sure if this is the correct approach:

var findUserByUsernameHelper = function (username){


return new Promise(function (resolve,reject) {
r.db("test").table("users").filter(function (user) {
    return user("name").match("(?i)^"+username+"$");
}).nth(0).default(null).run().then((result)=> {
 resolve(result);
}).error((err)=>{
reject(err);
});
});
}

Im not sure if wrapping a promise inside a new promise is the correct way to do it. Is there a better way I can create my own helper promise functions I could then use to build the api with?



via jimmy

No comments:

Post a Comment