0

I am trying to fetch data from from API using axios but it keeps returning a Promise

The code for nodeJs:

router.get('/isAdmin/:userId/:groupeId', async (req, res) => {
    let userId =  req.params.userId
    let groupeId =  req.params.groupeId
    let result = await db.query("select * from groupemembers where userId = ? and groupeId = ? and groupeRole = 'admin'",[userId, groupeId], function(err, result){
        if (err) console.log(err.message);
        if (result.length > 0) return res.send(true);
        else res.send(false)
    })
    return result
})

the Code for ReactJs:

 async function checkAdmin (){
        let user = JSON.parse(localStorage.getItem('userInfo'))
        let groupeId = params.groupeId
        let result = api.get(`/isAdmin/${user.id}/${groupeId}`).then(res => {
            return res.data
        })
        return result
    }
aouad sami
  • 77
  • 1
  • 7
  • 2
    What's wrong if it returns a promise? Isn't that expected? – Ramesh Reddy Jan 03 '22 at 10:03
  • 1
    just try this: await api.get(`/isAdmin/${user.id}/${groupeId}`); – HDM91 Jan 03 '22 at 10:05
  • 1
    @HDM91 why? how would that change anything? – Thomas Jan 03 '22 at 10:07
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await – HDM91 Jan 03 '22 at 10:09
  • 2
    You just have to use await/then where you're calling `checkAdmin` and get the resolved value – Ramesh Reddy Jan 03 '22 at 10:11
  • @HDM91 I know how async/await works and I can tell you that `await` won't change anything. Actually you could even remove the `async` keyword without changing anything. – Thomas Jan 03 '22 at 10:13
  • @Thomas I think there is a misunderstanding here, I assume he will use an await before checkAdmin when it was called. so if you use an await before api.get you can get the result otherwise it return a promise. – HDM91 Jan 03 '22 at 10:18
  • @HDM91 async functions *always* return a Promise, no exceptions. So your `await` is awaiting one Promise to get to the value *(not doing anything with it)*, only to then immediately wrap that value in a new Promise. – Thomas Jan 03 '22 at 10:28
  • @Thomas I said that he should call checkAdmin with await before to get the actual result, two await one before api.get and another with checkAdmin. – HDM91 Jan 03 '22 at 10:28

1 Answers1

-1

You are not using the await keyword for resolving the promise

 async function checkAdmin (){
            let user = JSON.parse(localStorage.getItem('userInfo'))
            let groupeId = params.groupeId
            let result = await api.get(`/isAdmin/${user.id}/${groupeId}`).then(res => {
                return res.data
            })
            return result
        }
Abhishek K
  • 117
  • 5