0

I am able to fetch data from database but returning this data as a response to a request made is the problem.

 `    // create employees and save into the databse
async save(resp) {

    this.bcrypt.hash(this.user.password, 10).then( (hash)=>{

        let params = [this.user.firstName,
            this.user.lastName,this.user.email, 
            this.user.password, this.user.gender, 
            this.user.jobRole,this.user.department, 
            this.user.address];

       this.client.query( 
        'INSERT into employees (firstName, lastName, email, password, gender, jobRole, department, address) VALUES($1, $2, $3, $4, $5, $6, $7, $8) RETURNING userId', 
         params)

        .then ( (result) => {

            try {
                let userFetched = result.rows[0].userid;
                this.client.query("SELECT * FROM employees WHERE userid = $1", [userFetched])
                    .then( (res)=>{

                        console.log(res.rows[0]);
                        return res.rows[0];

                    })

                    .catch( (err)=>{
                        console.log(err);
                    })


            } catch (error) {
                return {
                    error: "Employee could not be created correctly."
                }
            }

        })

        .catch( (err)=>{
            return {
                error: "Something went wrong. Try again later."
            }
        })


    })

}`

If I console the fetched data , that works but returning it is the problem. I keep getting an error. Please help.

Seyyid Said
  • 475
  • 2
  • 6
  • 16
  • by the way, why `async save(resp)` since you never use `await`? – Bravo Nov 10 '19 at 08:41
  • I wanted this to be an asynchronous function – Seyyid Said Nov 10 '19 at 08:44
  • sure, but then you can make your function really readable by using `await` instead of `.then` ... use one or the other, you hardly ever need to mix `async/await` with `.then` – Bravo Nov 10 '19 at 08:48
  • oh, did you think marking it `async` means you can get the result by saying `result = save(....)` - no, making a function `async` means it returns a Promise – Bravo Nov 10 '19 at 08:56
  • and will that affect the return statement ? – Seyyid Said Nov 10 '19 at 09:03
  • 1
    will what effect which return statement? Your `save` function currently returns a Promise that resolves to `undefined` ... if you remove `async` the `save` function will then return `undefined` as you never return anything directly from the `save` function ... here https://pastebin.com/2djRkenu is what your code looks like written as `async`/`await` – Bravo Nov 10 '19 at 09:13

0 Answers0