我遇到一个在console.log(usersOutput,'here')之后运行get_user()的问题。如何更改它以使get_user()首先运行?
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
}
答案 0 :(得分:2)
您可以使用axios promise和async / await。像这样:
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
}
答案 1 :(得分:2)
您不要将其设为异步,这将阻塞您永远不想做的线程。只需从函数返回promise并传递promise而不是数据即可:
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 */)
}