从async函数返回resolve-value

时间:2018-03-04 16:26:50

标签: javascript ecmascript-6 promise async-await

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



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

  return response;
};

console.log(getTs()); // Promise { <pending> }
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分: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 :(得分:1)

解决请求后,

getTs将得到解决。所以你必须等待响应:

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

  return response;
};

getTs().then(response => console.log(response));
相关问题