简体   繁体   中英

Async function return inside synchronous function

I have been working through this MDN async guide to better understand async code. Just as I felt like I was getting a better grasp of async code/promises, I ran into this function in that guide:

function fetchAndDecode(url, type) {
  return fetch(url).then(response => {
    if(!response.ok) {
      throw new Error('HTTP error! status: ${response.status}');
    } else {
      if(type === 'blob') {
        return response.blob();
      } else if(type === 'text') {
        return response.text();
      }
    }
  })
  .catch(e => {
    console.log(`There has been a problem with your fetch operation for resource "${url}": ` + e.message);
  });
}

My first inclination was to not get hung up on it and power through it, but of course, it builds off this example later in the guide and so I was hoping someone here could help me out with this specific situation; an async function running inside a synchronous function.

I console.log()'d the output, and am receiving what you would expect, a Promise object. I can see that because we are returning an async function(fetch), which returns another promise(.then), which returns another promise(.blob() or .text()).

I googled and looked around SO, but I couldn't find a question that explain this particular situation to me. I was hoping someone could either point me to a link, or explain this thoroughly enough so I don't feel like I'm stuck.

Does the fetchAndDecode() function get pushed to the async event queue, and only run once the main thread is available? If so, how does the code know to do this?

Why wrap this async code inside a sync declaration? Why wrap it at all?

Would it be more correct to declare

async function fetchAndDecode(url, type) {

    return await fetch(url).then( /* etc... */ )}

Thanks for your help.

Jordan

Does the fetchAndDecode() function get pushed to the async even queue

No. It's synchronous. It just calls a function ( fetch ) which triggers something asynchronous.

Why wrap this async code inside a sync declaration? Why wrap it at all?

It takes two arguments. It lets you reuse the function when those arguments change without duplicating the entire body.

Would it be more correct to declare

No, that's just more verbose.

await is useful when you want to pause a function until a promise resolves and then do something with the resolved value inside that function .

You aren't doing that. You're just returning.

"Return the promise returned from fetch" is a lot simpler than "Create a new promise (and return it). Wait for the promise returned from fetch to resolve, get its value, then resolve the first promise with that value."

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