【发布时间】:2019-05-08 11:29:40
【问题描述】:
请多多包涵,我已经投入到一个新项目中,并试图全力以赴。过去几天我一直在取得进展,但似乎无法克服最后的困难。希望我能正确解释。
我正在加载一个 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);
大多数时候我会在警报中返回正确的真或假,但有时我会返回未定义。我猜未定义是因为它在异步/等待完成之前到达警报。我的印象是它不会越过我称之为“test();”的那一行。我认为它实际上是让它停止低于 test(); 的任何东西。直到等待结束。最初它有点复杂,但我不断将其剥离以使其(希望)更基本/简单。
我的想法或实施中缺少什么?
非常感谢任何帮助,因为我现在正在追赶我的尾巴。
【问题讨论】:
-
您需要使用
await test()。 -
http.post()来自哪里?如果这是浏览器,那它不是内置在浏览器中的,所以它必须来自某个库。它来自哪个图书馆?它会返回一个承诺吗?
标签: javascript jquery rest promise async-await