0

I want to convert promise in to async await but I cannot find the right syntax for the function that reads the data from the response

export async function getDataFromServer(id) {
    try {

        const resp = await fetch('/dataget', {
            credentials: "same-origin",
            mode: "same-origin",
            method: 'POST',
            headers: { "Content-Type": "application/json" },
            body: `${id}`
        })

        const data = await resp.json()

        const handel = await function (data) {
            console.log(data);
            // render function 
            renderDataFromServer(data)
        }
    }
    catch (err) {
        if (err === "server") return
        console.log(err)
    }
}

8
  • What is the problem that you're facing? Commented Jun 7, 2021 at 23:14
  • what does renderDataFromServer() do? Commented Jun 7, 2021 at 23:16
  • 4
    Why would it run? handel is never called. I'm not sure what the point of const handel = await function (data) { is. I'd just remove that line. Commented Jun 7, 2021 at 23:17
  • 5
    await function(){} doesn’t make sense. A function expression doesn’t need awaiting. What are you expecting this to do? Commented Jun 7, 2021 at 23:18
  • 3
    If you wanted to run renderDataFromServer() after data from resp.json() returns, you could call it directly under the await call const data = await resp.json(); renderDataFromServer(data) Commented Jun 7, 2021 at 23:21

1 Answer 1

2

If you remove the unnecessary function declaration it should work:

export async function getDataFromServer(id) {
    try {

        const resp = await fetch('/dataget', {
            credentials: "same-origin",
            mode: "same-origin",
            method: 'POST',
            headers: { "Content-Type": "application/json" },
            body: `${id}`
        })

        const data = await resp.json();

        console.log(data);
        // render function 
        return renderDataFromServer(data);
    } catch (err) {
        if (err === "server") return
        console.log(err)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.