Async/Await 没有像我期望的那样等待

Ric*_*chP 1 javascript rest jquery promise async-await

请耐心等待,我已经被投入到一个新项目中,并试图将其全部吸收。在过去的几天里,我一直在取得进展,但似乎无法克服最后的困难。希望我能正确解释。

我正在加载一个 Web 表单,需要调用 API 来获取一些根据当前加载的数据可能存在或不存在的信息。我已经将我的页面简化为基本上是这样的。

...Get some information the user wants and start to do some work to load 
up the page and set up the form.
...old stuff working fine...

//Time for my new stuff
var testValue
async function test() {
    await http.post(appConfig.serviceRootUrl + '/api/XXX/YYY', 
    { mProperty: myObject.collectionInObject.itemInCollection }).then(function (result) {
        if (result.length < 1) {
            testValue= false;
        }
        else if (result[0].infoIWant.trim().length > 0) {
            testValue= true;
        }
    });
}
test(); 

//Originally above in the if I was just seeing if I got a result 
//and setting testValue to true/false but changed it for debugging 
//and I am surely getting back correct values when the data exists 
//or result.length zero when no data for it


...Do a bunch of more stuff that is old and working correctly....

//Test the new stuff up above

 alert(testValue);
Run Code Online (Sandbox Code Playgroud)

大多数时候我会在警报中返回正确的 true 或 false,但偶尔我会返回 undefined。我猜未定义是因为它在异步/等待完成之前收到警报。我的印象是它不会超过我称之为“test();”的行。我认为它实际上使它停止了 test(); 以下的任何内容。直到等待结束。最初它有点复杂,但我不断地将其剥离以使其(希望如此)更加基本/简单。

我的想法或实施中缺少什么?

非常感谢任何帮助,因为我现在正在追赶我的尾巴。

Mar*_*yer 5

这不是异步函数的工作方式。该函数似乎只在函数本身内部等待。在函数外部它被调用并同步返回一个承诺。

换句话说,如果你写:

 let t = test()
Run Code Online (Sandbox Code Playgroud)

t将是一个在返回时解决的承诺test()。在您当前的代码中,如果您想在函数外部响应,您将需要类似的内容:

async function test() {
    let result = await http.post(appConfig.serviceRootUrl + '/api/XXX/YYY', 
    { mProperty: myObject.collectionInObject.itemInCollection })
    if (result.length < 1) return false
    else if (result[0].infoIWant.trim().length > 0)  return true;
}


// test is an async function. It returns a promise.
test().then(result => alert("result: " + result ))
Run Code Online (Sandbox Code Playgroud)

根据评论进行编辑
这是使用 Axios 执行 http.post 命令的工作版本:

 let t = test()
Run Code Online (Sandbox Code Playgroud)
async function test() {
    let result = await http.post(appConfig.serviceRootUrl + '/api/XXX/YYY', 
    { mProperty: myObject.collectionInObject.itemInCollection })
    if (result.length < 1) return false
    else if (result[0].infoIWant.trim().length > 0)  return true;
}


// test is an async function. It returns a promise.
test().then(result => alert("result: " + result ))
Run Code Online (Sandbox Code Playgroud)