【问题标题】:Async/Await func doesn't wait to console.log it's responseAsync/Await 函数不等待 console.log 它的响应
【发布时间】:2019-04-17 23:20:10
【问题描述】:

我正在尝试创建一个异步函数并将它的响应保存到一个变量,然后 console.log 该变量,但它是在异步函数完成之前 console.logging 响应。

import axios from 'axios';

async function getItems() {
  const response = await axios.get(SOME_URL);
  console.log('done', response);
  return response;
}

const items = getItems();
console.log('items: ', items);

我希望日志看起来像这样:

// Expected result
done: {...result...}
items: {...items...}

但我实际上得到的是:

// ACTUAL result
items: Promise {<pending>}
done: {...result...}

我想等到请求完成后再继续我对getItems 的调用。

我错过了什么?

【问题讨论】:

  • 如果你想等待结果,你应该等待getItems
  • const items = await getItems() 或使用then()
  • 使用 async/await 不会神奇地使异步行为同步。它实际上只是返回承诺的函数的语法糖;当你调用函数时,你仍然需要处理这个promise,要么从另一个异步函数调用它,要么链接thens。

标签: javascript node.js asynchronous async-await axios


【解决方案1】:

由于“getItems”是异步调用,因此您将在“.then”中获得结果,如下所示

import axios from 'axios';

async function getItems() {
  const response = await axios.get(SOME_URL);
  console.log('done', response);
  return response;
}

getItems().then(items => console.log('items: ', items))

【讨论】:

  • 另外,如果你想在 getItems() 函数中处理执行,你也可以在函数中执行 try {} catch(error){} 然后调用 getItems() ,确保你用里面的 await 函数包装你的 try 块。请记住,在异步过程中捕获错误始终很重要
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-23
  • 1970-01-01
  • 2021-12-11
  • 2016-03-08
  • 1970-01-01
  • 2019-08-14
  • 1970-01-01
相关资源
最近更新 更多