首页 > 解决方案 > How do I turn a javascript ajax caller function into async/await?

问题描述

Let's say I have the following function getData

getData = (param) => {
    // jquery
    $.ajax(...).done(..)
}

How do I turn getData into a blocking function so that refreshPage only gets called after the ajax within getData is done?

data = getData(..)
refreshPage()

Please note: I don't want to pass refreshPage into the ajax callback within getData

OK... here is what I tried and seems working:

getData = (param) => {
    // jquery
    return $.ajax(...).done(..)
}
getData.then(refreshPage())

标签: javascript

解决方案


function getData = (param) => {
    // jquery
    return $.ajax(...);
}

async test() {
    var x = await getData()
    console.log(x)
}

推荐阅读