If I understand right I should be able to get the promise the way like that:
var helper = null;
MyModel.findAll().then(result => { helper = result });
In the examples this should be enough, but I do not get anything. If I assign a variable for the whole call I get promise pending. The only "difference" I see from the examples is that I call it in an http request:
exports.somePostRequest = (req, res, next) => {
var helper = null;
myModel.findAll().then(result => { helper = result });
}
This works perfectly:
exports.anOtherrequest = (req, res, next) => {
myModel.findAll()
.then(result => {
res.status(200).json({message: result})})
}
Some of the examples I was looking at: https://sequelize.org/v3/docs/models-usage/ How to update a record using sequelize for node?
Any suggestion why this does not work?
CodePudding user response:
var helper = null;
MyModel.findAll().then(result => { helper = result });
console.log(helper) // will be null
The problem with the approach above is that asynchronous operations like the one on line 2 will not happen in the order you expect it to. What happens in javascript is that line 1 executed, line 2 (asynchronous operation) is scheduled to run after all the synchronous operations gets executed, and line 3 runs, and finally all the asynchronous operations will complete (line 2 in this case).
So in simple words, the order of execution here is:
line 1 completes >> line 2 is scheduled to complete later >> line 3 completes >> line 2 operation completes
You can instead use await
to make it go in order. Something like:
var helper = null;
helper = await MyModel.findAll();
console.log(helper); // not null; yayy
This way everything runs in order. But keep in mind, await operations should be inside an async
function. So you're server should look something like:
exports.somePostRequest = async(req, res, next) => {
var helper = null;
helper = await myModel.findAll();
// or, var helper = await myModel.findAll();
// then do what you want with helper
}
Alternative solution using .then
exports.somePostRequest = (req, res, next) => {
myModel.findAll().then(result =>
{
// work with the result here !
// console.log(result);
});
}