简体   繁体   中英

Return resolve-value from async function

In my project I use promise (code below), how it is possible, that promise still pending , when I used keyword await . Can someone help me figure out, what I'm doing wrong?

 const getTs = async () => { const response = await axios.get('...') .then(res => res.data) .catch(() => 'ERROR'); return response; }; console.log(getTs()); // Promise { <pending> } 

The await does only stop the execution of the async function body, nothing else. The caller is not blocked, the code is still asynchronous, and you get back a promise. If you want to log the result, you have to wait for it.

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

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

or

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();

getTs will be resolved once the request is resolved. So you have to await the response like :

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

  return response;
};

getTs().then(response => console.log(response));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM