You're using async/await incorrectly. The callback function has to be an async function as well, i.e.:
this.model('Template').findById(id, async function (err, doc) {
let ref = await getNextSequence();
...
});
To be honest, if you're going to use async/await, you should just use promises (findById returns a Promise
if you don't pass it a callback).
try {
const doc = await this.model('Template').findById(id);
let ref = await getNextSequence();
...
} catch (error) {
handleError(error);
}
This avoids nested async function bugs like this that can be tricky to catch.
@varunjayaraman
try {
const doc = await this.model('Template').findById(id);
let ref = await getNextSequence();
...
} catch (error) {
handleError(error);
}
In an Express middleware,
dbtitle = await Title.find({id: req.params.id}).exec();
^^^^
the code above code does not work on me. Getting unexpected identifier error on Title.
Both code logically the same. Both returns promises.
@inanmadak i can't repro without a full repro script. I've done something similar to that many times with async/await and it has worked for me
The unexpected identifier error is a syntax error that usually means that await
is used in a function that isn't marked async
. For example, the below function will error:
async function test() {
[1, 2].forEach(function() {
await new Promise(resolve => setTimeout(() => resolve(), 50);
});
}
Because await
is inside the closure passed to forEach()
, which is not async. I wrote a couple articles on async/await to help people grok the fundamentals:
Make sure you check them out if you're new with async/await
Most helpful comment
You're using async/await incorrectly. The callback function has to be an async function as well, i.e.:
To be honest, if you're going to use async/await, you should just use promises (findById returns a
Promise
if you don't pass it a callback).This avoids nested async function bugs like this that can be tricky to catch.