Forgive me but I am new to JS promises. I think I need to use one for interacting with an AWS service, which writes to and pulls data from DynamoDB. I have a JavaScript app which is ran by the Serverless npm plugin, which defines exported functions as end points. In these endpoints after the promise has completed I need to bubble the data back up to the endpoint to expose it as a JSON body. See the code below.
exports.getBlog = async (event) => {
return getBlogPost(event).then((data) => {
console.log("worked", data);
var response = {
statusCode: 200,
body: JSON.stringify(data)
};
return response;
})
.catch((error) => {
console.log("didn't work");
var response = {
statusCode: 400,
body: JSON.stringify(error.toString())
};
return response;
});
}
What makes me think it's not right is that I have to create a var response
and return it, and then return again outside of that in the root of exports.getBlog
. Is this right? It makes the JSON print correctly, but am confused from reading tutorials online as to whether this is good practice?
If not, how would you return data from the promise and expose it as a JSON result?
In this example, exports.getBlog
is referenced by the Serverless framework as an endpoint, like so:-
functions:
get-blog:
handler: api/blog.getBlog
events:
- http:
path: api/v1/blog
method: GET
cors: true
You are mixing the two. Here is with async/await
exports.getBlog = async (event) => {
try {
var res = await getBlogPost(event);
var data = res.data;
console.log("worked", data);
var response = {
statusCode: 200,
body: JSON.stringify(data)
};
return response;
} catch(error) {
console.log("didn't work");
var response = {
statusCode: 400,
body: JSON.stringify(error.toString())
};
return response;
}
}
and without
exports.getBlog = event => {
return getBlogPost(event).then((data) => {
console.log("worked", data);
var response = {
statusCode: 200,
body: JSON.stringify(data)
};
return response;
})
.catch((error) => {
console.log("didn't work");
var response = {
statusCode: 400,
body: JSON.stringify(error.toString())
};
return response;
});
}
EDIT: adding MDN's article on async/await and how one can rewrite promise code with it