14

I am experiencing an issue where get_user() is running after console.log(usersOutput, 'here'). How can I change it such that get_user() run first?

function get_user(user){
        axios.get(`/api/admin/users`,{params:{idnum:user}}).then((user)=>{
           console.log('got user')
           return user.data
        })
}

var UsersFormatter = function(c){
    let usersOutput = 'waiting for change'
    var usersOutput = get_user(c.cell.row.data.sessionUser)
    console.log(usersOutput,' here')
    return usersOutput
}
ApplePie
  • 1,155
  • 3
  • 12
  • 30

2 Answers2

14

You don't make it synchronous, that will block the thread, which you never want to do. Just return the promise from the function and pass the promise around instead of the data:

function get_user(user){
    // return this promise
    return axios.get(`/api/admin/users`,{params:{idnum:user}}).then((user)=>{
        console.log('got user')
        return user.data
    })
}

var UsersFormatter = function(c){
    // return this promise too, so callers of UserFormatter can get the data 
    return get_user(c.cell.row.data.sessionUser)
    .then((data) => /* format data and return */)
}
Mark
  • 90,562
  • 7
  • 108
  • 148
  • 2
    What about web worker? I feel fine blocking web worker thread. – daliusd Jan 31 '19 at 22:07
  • It seems *very* unlikely the OP is using web workers and asking this question in this form. But if you recommend using Axios synchronously in a web worker, please post an answer. I'd be curious to learn about that. – Mark Mar 04 '21 at 00:39
  • I have ended up using async/await in web worker. I think that's good approach as you don't need to learn different approach for main thread and web worker threads. – daliusd Mar 05 '21 at 07:52
6

You can make use of the axios promise and use async/await. So something like this:

function get_user(user){
        return axios.get(`/api/admin/users`,{params:{idnum:user}})
}

var UsersFormatter = async function(
    let usersOutput = await get_user(c.cell.row.data.sessionUser)
    console.log(usersOutput,' here')
    return usersOutput
}
Aldo Sanchez
  • 450
  • 7
  • 23