Javascript 如何使 axios 调用同步?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51564001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:51:57  来源:igfitidea点击:

how to make axios call synchronous?

javascriptnode.js

提问by ApplePie

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?

我遇到了 get_user() 在 console.log(usersOutput, 'here') 之后运行的问题。如何更改它以便 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
}

回答by Mark Meyer

You don'tmake 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 */)
}

回答by Aldo Sanchez

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

您可以使用 axios 承诺并使用 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
}