【问题标题】:How to return an Ajax result using async/await? [duplicate]如何使用 async/await 返回 Ajax 结果? [复制]
【发布时间】:2021-08-23 18:40:14
【问题描述】:

为了熟悉async/await,我在Chrome中尝试了以下代码:

async function f() { 
     return await $.get('/');
};
var result = f();

result 不保存结果(字符串);相反,它拥有一个Promise,需要再次等待。这段代码确实给了我响应字符串:

var response = await $.get('/');

如何使用 await 从函数返回实际的响应字符串?

【问题讨论】:

  • async/await 并不能神奇地解决从异步函数返回的问题。在某个地方,您仍然需要等待结果。在这种情况下,您需要在 result 上添加一个 .then()
  • var result = await f(); 会很好用

标签: javascript jquery ajax asynchronous async-await


【解决方案1】:

要么

function f() { 
  return $.get('/');
};

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

test()

f().then(function(res) {
    console.log(res)
}

async/await 只是编写相同逻辑的另一种方式。

【讨论】:

  • 那么我在 f() 中添加的额外 await 有什么作用?
  • @user3599803 什么意思?
  • 在我上面的代码中,我在f()里面写了return await $.get('/');,这个await没用吗?
  • 是的,当您调用f() 方法时,此等待无效。如果您想在 f() 内编写更多代码行,您的 await 将是有意义的:f() { let res = await $.get('/'); console.log(res) };
【解决方案2】:

awaitasync 基本上只是Promise 之上的语法糖。如果你最后得到一个Promise,你仍然需要像对待Promise一样对待它。

const response = f().then(() => { });

或者,如果您在异步函数内部调用它,您可以等待解决它:

async function main() {
  const response = await f();
  console.log(response);
}

我喜欢使用的一种模式是将我的主要代码包装在一个自执行的异步函数中,这样我仍然可以使用 await:

(async () => {
  const result = await doSomething();
  console.log(result);
})();

请注意,即使使用这种模式,我也需要一个最终的catch() 来捕获它可能存在的任何其他方式无法捕获的错误:

(async () => {
  // blah blah
})().catch(() => {});

【讨论】:

    【解决方案3】:

    异步函数的返回类型是 Promise。所以你必须等待或 then() 才能得到结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-04
      • 2021-10-21
      • 1970-01-01
      • 2018-09-05
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      相关资源
      最近更新 更多