I'm new to using async/await in nodejs and am confused about how to return data that I want for use in a view. Here is my code. below is the homeController, which is used like so: app.get("/", homeController.index);
I tried making the index
method async, but i still can't console out the news data. what is the right way to resolve the article information so it's available for consumption in the view in home
?
async function getNewsData() {
const pool = await connection;
const result = await pool.request()
.input("StoryID", sql.Int, 154147)
.execute("News.uspStoryByIdGet");
console.log(result, "the result from the stored procedure");
return result;
}
const article = getNewsData().
catch((e) => {
console.log("the error", e);
});
export let index = async(req: Request, res: Response) => {
const article = await getNewsData();
console.log(article, "yoo");
res.render("home", {
article,
title: "Home",
});
};
No value is return
ed from getNewsData()
function call, see Why is value undefined at .then() chained to Promise? You can return row
from getNewsData()
if expected result of getNewsData()
call is rows
array.
for what I can see you should probably not be await
ing for connection
in your getNewsData
unless for some reason connection
is a promise that is was or is waiting to be resolved.
you should also be returning result
on getNewsData
function.
If that is not what is causing the problems there here are some clarifications about async/await
1 - Calling an async function behaves similar to calling a function that returns a Promise
2 - when you use await
its behaves as if you wait for a promise to be resolved and extract the result from it, which you would have in your scope instead of having passed to a callback function in the then
or catch
methods.
feel free to reply to this answer if still in doubt.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.