2

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",
  });
};
devdropper87
  • 4,025
  • 11
  • 44
  • 70

2 Answers2

0

No value is returned fromgetNewsData() 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.

guest271314
  • 1
  • 15
  • 104
  • 177
0

for what I can see you should probably not be awaiting 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.

jenriquer
  • 166
  • 2
  • 1
    check this out @devdropper87, make any modifications here and send back another pen so we are in the same page https://codepen.io/anon/pen/PJELxX?editors=0010 – jenriquer Oct 06 '17 at 02:42