Reputation: 17067
I have this existing function, which works fine:
const fetchWrapper = (resource, init) => {
console.log('About to fetch...', resource)
const p = fetch(resource, init)
p.then(
(response) => {
console.log('The response is:', response)
},
(error) => {
console.log('The error is:', error)
}
)
return p
}
I try to use async/await whenever possible. However, I am thinking that it's not actually possible to do so.
The main issue is that I want to return the promise returned by fetch()
, so that the calling function can await
as it would normally do.
But I also want extra things to happen just before calling fetch()
(that's the easy part) and then straight after a network response.
To do that, I am attaching two callback (response and error) to the promise returned by fetch()
.
If I were not to use promises, I would have to await
for the fetch()
call -- but then the caller won't receive the response till the promise is resolved, which is not what I want.
So... is it even possible to convert this code to full async/await?
Upvotes: 1
Views: 110
Reputation: 4627
The code below, which uses async and await, does the same thing as your code:
// A simple promise response
const mockFetch = async (resource, init) => 'Response'
const fetchWrapper = async (resource, init) => {
console.log('About to fetch...', resource)
// You'll replace 'mockFetch' with 'fetch'
const p = mockFetch(resource, init);
// You can use a named function instead
(async () => {
try {
const response = await p
console.log('The response is:', response)
} catch (error) {
console.log('The error is:', error)
}
})()
return p
}
(async () => {
const response = await fetchWrapper('', {})
console.log(response)
})()
mockFetch
is for demonstration purpose, you'll need to remove and replace const p = mockFetch(resource, init);
with const p = fetch(resource, init);
Upvotes: 1
Reputation: 2734
For ommiting usage of .then()
/ .catch()
you could go with this:
const fetchWrapper = (resource, init) => {
// do stuff before fetch here ^^
// ...
// call the fetch
const p = fetch(resource, init)
const afterFetchEffects = async () => {
// since it is "detached" (i call it like so..)
// you should ofc use try/catch
try {
// wait for the fetch() to finish
await p
// do some stuff after fetch
// ...
} catch(err) {
console.error('Error in detached after fetch promise..', err)
}
}
// execute the wrapper which executes something after the fetch..
// do not await it then it will do its own business.
afterFetchEffects()
// pass fetch immediatly back
return p
}
I am not sure which approach is more readable^^
Upvotes: 0
Reputation: 20334
Maybe something like this:
const fetchWrapper = async (resource, init) => {
try {
const response = await fetch(resource, init);
console.log('The response is:', response);
return { success: true, response };
} catch(error) {
console.log('The error is:', error);
return { success: false, error };
}
}
Upvotes: 1
Reputation: 20
const getData = async () => {
try{
const fetchData = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
if (fetchData.ok == true) {
const respons = await response.json();
return respons;
} else {
throw new Error("error")
}
} catch (err) {
console.log(err)
}
}
Upvotes: 0
Reputation: 195
async function fetchPost() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {headers: {"Content-Type": "application/json"}});
const post = await response.json();
console.log(post)
return post;
}
fetchPost() // Returning a Promise with the post
Upvotes: 0