0

I want to return what I get after an async call.

So

app.get("/books", async (req, res) => {
    let books = await getBooks()
        .then(json => {
            res.status(200).send({"books": json});
        }); 
});

Should wait on rendering the result until the called getBooks is done.

export async function getBooks() {
    console.log("Getting books from cloud");
    Book.findAll({
        // ...

    }).then(books => {
        console.log("Got books");
        return JSON.stringify(books, null, 4);
    });
}

But right now the response gets rendered without actually waiting for the result.

Saphire
  • 1,812
  • 1
  • 18
  • 34
  • Check this: https://javascript.info/promise-chaining or this https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call It's probably gonna help you. – Naor Levi Jan 23 '20 at 07:29

4 Answers4

2

You don't need to use promises. You can just use await and then use the result of that.

 app.get("/books", async (req, res) => {
   const books = await getBooks();
   res.status(200).send({ books });
 });

I'd highly suggest taking it a step further and using try/catch to handle failure cases

 app.get("/books", async (req, res) => {
   try {
     const books = await getBooks();
     res.status(200).send({ books });
   } catch (error) {
     // massage this to send the correct status code and body
     res.status(400).send( { error });
   }
 });
VtoCorleone
  • 16,813
  • 5
  • 37
  • 51
  • Correct and my answer was somewhat misleading. I know async/await uses promises under the hood but I didn't want to get into that deep of a conversation for this answer :D – VtoCorleone Jan 24 '20 at 04:19
0

You can use await in second method too:

export async function getBooks() {
console.log("Getting books from cloud");
var books = await Book.findAll({
    // ...

})
 if(books){
     console.log("Got books");
    return JSON.stringify(books, null, 4);
  }
0

You just need to return your promise, and since you're just returning a promise you don't need async;.

app.get("/books", async (req, res) => {
    let json = await getBooks()
    res.status(200).send({"books": json});
});

export function getBooks() {
    console.log("Getting books from cloud");
    return Book.findAll({
        // ...

    }).then(books => {
        console.log("Got books");
        return JSON.stringify(books, null, 4);
    });
}
Cody G
  • 8,368
  • 2
  • 35
  • 50
0
app.get("/books", async (req, res) => {
    let books = await getBooks();
    res.status(200).send({"books": books});
})
Nandita Sharma
  • 13,287
  • 2
  • 22
  • 35
Dilip Kale
  • 71
  • 7