从async函数返回resolve-value

问题描述 投票:0回答:2

在我的项目中,当我使用关键字pending时,我使用promise(下面的代码),如何可能,这个承诺仍然是await。有人可以帮我搞清楚,我做错了什么?

const getTs = async () => {
  const response = await axios.get('...')
    .then(res => res.data)
    .catch(() => 'ERROR');

  return response;
};

console.log(getTs()); // Promise { <pending> }
javascript ecmascript-6 promise async-await
2个回答
3
投票

await只停止执行async function身体,没有别的。调用者没有被阻止,代码仍然是异步的,你得到了一个承诺。如果要记录结果,则必须等待它。

const getTs = () => axios.get('...').then(res => res.data).catch(() => 'ERROR');

getTs().then(console.log);
//     ^^^^^

要么

async function getTs() {
  try {
    const res = await axios.get('...');
    return res.data;
  } catch (e) {
    return 'ERROR';
  }
}

async function main() {
  const response = await getTs();
//                 ^^^^^
  console.log(response)
}
main();

1
投票

一旦请求得到解决,getTs将得到解决。所以你必须等待响应,如:

const getTs = async () => {
  const response = await axios.get('...')
    .then(res => res.data)
    .catch(() => 'ERROR');

  return response;
};

getTs().then(response => console.log(response));
© www.soinside.com 2019 - 2024. All rights reserved.