Home > Software engineering >  fetch res.json() working with await and async but not working with promises
fetch res.json() working with await and async but not working with promises

Time:08-06

I have always been made to believe that async and await and promises were one and the same thing, here, in my code, res.json() is working with await but isnt working at all with .then(). maybe I am missing something. please this is not a duplicate question. I have been scouring the internet for answers for the most part of two days now.

Here is the code with .then, aync and await, and i will also include the code from my server that sends the json

CODE USING .then()

const requestURL = "/auth/profile";

const request = new Request(requestURL, {
    method: 'POST'
});
fetch(request)
    .then( (res) => {
        res.json()
    })
    .then(obj => {
        console.log(obj)
    })
    .catch(err => {
        console.log(err)
    })

here, console.log(obj) logs undefined

CODE USING ASYNC AND AWAIT

const requestURL = "/auth/profile";

const request = new Request(requestURL, {
    method: 'POST'
});
fetch(request)
    .then( aync (res) => {
        const obj = await res.json()
        console.log(obj)
    })
    .catch(err => {
        console.log(err)
    })

here, console.log(obj) logs the correct json object as expected

server request handler (nodejs)

const getProfile = async (req, res, next) => {
    
    const result = JSON.stringify({"status":"not logged in", "body": "there is a big poblem"})

    res.setHeader('content-type', 'application/json');
    
    res.status(200).send(result)

}

While I have used other tools to make sure I have the response from my server properly set up, if i am missing something kindly indicate to me, cheers

CodePudding user response:

The problem is in your handling of of the chains. You need to return data to the next then, it's not automatic and varies depending on scope. Change to:

fetch(request)
.then( (res) => {
    // Process.. then return some data to the next chain in line.
    return res.json()
})
.then(obj => {
    // Now, obj will be what the line above 'returned'
    console.log(obj)
})
.catch(err => {
    console.log(err)
})
  • Related