elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

Async await friendly? :) #1

Closed MartinMuzatko closed 7 years ago

MartinMuzatko commented 7 years ago

Hey there! This looks like a nice lib. Good work so far!

I wanted to know, if wretch is good with async/await. Since res is a callback and not a promise. Does wretch return a promise?

elbywan commented 7 years ago

Hey there! This looks like a nice lib. Good work so far!

Many thanks 👍 !

I wanted to know, if wretch is good with async/await.

Absolutely !

Since res is a callback and not a promise. Does wretch return a promise?

res (and all response type methods such as json, formData ...) always return a Promise object.

If you do not pass a callback, the Promise encapsulates the expected types (res : Response, json: Object, formData: FormData and so on ...)

If you call the function with a callback, the Promise will encapsulate the type returned by the callback.

A tiny example :

// response contains the Response object
const response = await wretch("...").get().res()
// jsonObject contains the deserialized json
const jsonObject = await wretch("...").get().json()
// number of keys contained in the json
const nbOfKeys = await wretch("...").get().json(_ => Object.keys(_).length)

And of course you can wrap the code inside a try/catch.

You can check out the tests for some code samples using async/await.

MartinMuzatko commented 7 years ago

Awesome! Thank you a lot for clarifying this :) I'm looking forward to test it :)

Naramsim commented 7 years ago

@MartinMuzatko Everything which returns a Promise is Async/Await friendly 👍