DEV Community

Discussion on: Beginners Guide To Fetching Data With (AJAX, Fetch API & Async/Await)

Collapse
 
itachiuchiha profile image
Itachi Uchiha • Edited

Is there a way extract data from promise? For example, I don't want to use like this:

blah().then()
Collapse
 
bjhaid_93 profile image
/[Abejide Femi Jr]\s/

don't know of any, apart from .then(), and .catch() -> for errors.

Collapse
 
maccabee profile image
Maccabee

You can await Promises.

const data = await blah();

That's how async/await compile with babel, into Promises.

Collapse
 
pierrejoubert73 profile image
Pierre Joubert

Ah much better xD

Collapse
 
itachiuchiha profile image
Itachi Uchiha

Thanks a lot. It worked :) Why I didn't try that. I think I was confused.

Collapse
 
pierrejoubert73 profile image
Pierre Joubert

Do you not like the syntax? Or do you not want to deal with promises?

Collapse
 
itachiuchiha profile image
Itachi Uchiha

I just wonder about assign result to a variable. I don't wan't to use then all time. For example:

const myResults = fetch('site.com')
   .then(resp => resp.json())
   .then(obj => obj)

console.log(myResults)
// { name: 'John', surname: 'Doe' }

Thread Thread
 
pierrejoubert73 profile image
Pierre Joubert • Edited

I just did this and it seemed to work:

var foo = null;
fetch('https://jsonplaceholder.typicode.com/posts/1')
   .then(resp => resp.json())
   .then(obj => foo = obj)

Then foo is accessible object like: foo.title
"sunt aut facere repellat provident occaecati excepturi optio reprehenderit"

Thread Thread
 
itachiuchiha profile image
Itachi Uchiha

Thanks a lot. That's exactly what I want.