Excerpt of a lambda function using nodejs 12. There is a promise (aws dynamo db document client query) nested inside a promise (node-fetch API request).
The first promise works fine. It executes the request, waits for the promise to resolve, and then enters the .then(...)
to execute some code. Next, it executes the database query, but then it exits the whole function without waiting for the promise to resolve, even though there are still callbacks. It doesn't throw errors either. (I know the database query is being executed , as extra logging showed it's status to be <pending>
)
When I try var dbscan = await db.scan(...)
using await
, I get the error await is only valid in async function
. But the handler function is already async, and await is working for the fetch promise.
Q: how can I use await
inside the .then(...)
of the first promise?
Q: why is the process exiting without waiting for the promise to resolve?
exports.myhandler = async (event, context, callback) => {
var response = await fetch(url, {... my options ...})
.then(res => res.text())
.then(data => {
// do some stuff with the data ...
var dbscan = db.scan({...my params ...}).promise()
.then(res => {
// do some stuff with result ...
callback(null, <some message>);
}).catch(err => {
console.log(err);
callback(null, <some message>);
});
})
.catch(error => {
console.log('error', error);
callback(null, <some message>);
});
}
CodePudding user response:
You have to add async
to the beginning of the function in which you want to use await
.
.then(async(data) => {
var dbscan = await ...
})
CodePudding user response:
Since you're already using the async/await
-syntax, you shouldn't have to resolve to using .then(..)
chains.
You could flatten most of your code like this:
const response = await fetch(url, {... my options ...});
const data = await response.text();
// Do some stuff with the data...
const result = await db.scan({...my params ...});
// Do some stuff with the result...