1

I am fetching an API service by using async await which one doesn't work properly because the reason I couldn't figure out. API connection at the below. You can see the all console.logs in order. When I run the code I am getting and Output like this :

// first step // fourth step Promise {}[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: Array(1) // second step // third step

It should wait to return until 'await response' finish the process but it doesn't. If you can see the problem let me know please. Appreciated...

async function postData(payload) {
    console.log('first step')
    const response =  await fetch("https://smarty.kerzz.com:4004/api/mock/getFeed", {
        body: JSON.stringify(payload),
        headers: {
            Accept: "application/json",
            Apikey: "bW9jay04ODc3NTU2NjExMjEyNGZmZmZmZmJ2",
            "Content-Type": "application/json"
        },
        method: "POST"
        })
    console.log('second step')
    const data = await response.json().then(data => data.response)
    console.log('third  step')
    return data
}

const a = postData(payload)
console.log('fourth step ' , a)
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • use `const a = await postData(payload)` and it will work as you expect – R4ncid Aug 19 '22 at 14:47
  • I have tried that but I am getting an error like : Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules – ctamyildirim Aug 19 '22 at 14:50
  • you can use await only in an async function, you can change you code like this `postData(payload).then(a => console.log('fourth step ' , a))` – R4ncid Aug 19 '22 at 14:53

0 Answers0