I've been searching through older answers, however can't figure out how to set it up for my specific use case, also many answers seem to be outdated.
Node.js console was warning about promise library being deprecated, so I tried to use Bluebird (to no avail). If there's another solution, I'm up to it, don't have to be Bluebird.
This is my code:
let shortInt;
count().then(result => shortInt = result).catch(err => console.log(err));
console.log("shortInt " + shortInt);
//doing some other stuff here
And the function I need to wait for result for:
async function count() {
let answer;
await Url.findOne({}).sort({short_url:-1}).exec(function (err,ur) { if (err) return err; answer = ur.short_url });
console.log("answer " + answer);
return answer;
}
For console.log(shortInt) I get 'undefined', and console.log(answer) always gets printed at the end, after all the //doing other stuff.
What do I need to change so that shortInt is set before I procede to //do other stuff.
I have set mongoose.Promise = require("bluebird"); to not get deprecated warning.
Your script actually continue to run before count()
result comes back, Node execute the main thread before async operations.
You can move your code to the scope of the resolving promise.
count()
.then(shortInt => {
// we can access shortInt here
// rest of code ...
})
.catch(err => console.log(err));