0

I have read some topics related to this but did not help, or I could not make them work. I have:

exports.findBookRating = (book) => {
var average;
Review.findAll({
    where: {
        bookId: book.id
    },
    attributes: [[sequelize.fn('avg', sequelize.col('rating')), 'avg_rated']],
    raw: true
})
.then(number => {
    average = number[0].avg_rated;

    console.log(average); //this works
})
.catch(err => {
    console.log(err);
});

console.log(average) // this does not work
}

I wanted to return number[0].avg_rated, and that is why I created that average variable but it did not work, can you please help me? Thank you!

  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Dave Newton Jun 07 '19 at 20:49

2 Answers2

0

"Promise.findA" is async, while the rest is sync. Your last line will execute before your Promise resolved and thus returning "undefined".

Seltsam
  • 854
  • 1
  • 7
  • 27
0

your Review.findAll is asynchronous which means right after it's called, it'll proceed to your console.log(average) // this does not work

And since it is asynchronous, by the time the console.log(average) // this does not work is called, average might not have yet been set.

Continue your code inside the .then part or use await if you need the value from an async call.

Example of using await:

const number = await Review.findAll()
const average = number[0].avg_rated
captainskippah
  • 1,350
  • 8
  • 16