【发布时间】:2021-03-27 19:08:56
【问题描述】:
我有一个 Rest API 端点 /foo/bar,我从异步函数 bar() 调用它,我从另一个函数 foo () 调用该函数,就像这样
async function bar () {
let result;
result = await $.ajax({}); /* pseudocode only */
return result;
}
function foo () {
let result;
result = bar ();
console.log ('This should display before the result, not after it');
console.log (result);
console.log ('This should display after the result, not before it');
foo();
我得到不一致的结果,我想知道是不是因为我需要像这样使 foo 异步
async function bar () {
let result;
result = await $.ajax({}); /* pseudocode only */
return result;
}
async function foo () {
let result;
result = await bar ();
console.log ('This should display before the result, not after it');
console.log (result);
console.log ('This should display after the result, not after it');
foo();
基本上我的问题是异步函数中的 await 是否会呈现该函数同步(即它阻塞调用函数直到 await 返回)?
【问题讨论】:
-
是的 - 否则你只会得到承诺`
-
你不能在 javascript 中阻止函数
-
是的,
await停止执行函数(并且只停止函数!)直到 promise 解决。然而,这实际上是异步函数异步的原因,因为您不知道何时继续执行。
标签: javascript ajax asynchronous