0

I am trying a little experiment here using Async without the Await. So what I did here is using Async with promise in the Fetch API. I am not getting the return in line 14 but line 8 works fine. Attached is the code. What should it have been? Thanks a lot and in advance.

async function getUserAsync(name) 
{
  let data
  fetch(`https://api.github.com/users/${name}`)
  .then(response => response.json())
  .then(response => {
    data = response
    console.log(data)  //line 8
  })
  return data
}

getUserAsync('john')
  .then(data => console.log(data))  //line 14
2
  • Did you mean to assign fetch to data? To answer your question: yes you can but you need to make sure your function returns a promise. Otherwise whatever it returns will be wrapped in one that immediately resolves. Sometimes it's not what you want; and certainly not in your specific case. Commented Jun 14, 2020 at 4:58
  • Duplicate Question, check the answer in the below link stackoverflow.com/a/77946819/2980414 Commented Feb 6, 2024 at 10:08

2 Answers 2

4

You can return the fetch() and you can get Promise object.

async function getUserAsync(name) {
  return fetch(`https://api.github.com/users/${name}`)
    .then(response => response.json())
}

getUserAsync('john')
  .then(data => console.log(data))

Sign up to request clarification or add additional context in comments.

Comments

2

Or you can create and return a custom Promise from your async function:

async function getUserAsync(name) 
{
  return new Promise((resolve, reject) => {
    let data
    fetch(`https://api.github.com/users/${name}`)
    .then(response => response.json())
    .then(response => {
      data = response
      console.log(data)  //line 8
      resolve(data)
    })
    .catch(error => reject(error))
  })
}

getUserAsync('john')
  .then(data => console.log(data))  //line 14

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.