我有一个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返回?
发布于 2021-03-28 03:13:16
你是对的。异步函数将返回一个Promise,因此,如果您想等待异步函数的响应,则需要await。
发布于 2021-03-28 03:13:39
根据定义,async函数是returns a Promise,因此您可以像处理任何其他Promise一样处理结果。
这基本上意味着您要么使用async/await执行第二个代码片段中的操作
async function foo () {
let result;
result = await bar ();
console.log (result);
}或者您也可以使用.then
function foo() {
bar().then(result => console.log(result));
}https://stackoverflow.com/questions/66835149
复制相似问题