How would I go about converting this to use async/await instead of fetch? Sorry, I'm really confused on the subject and would really appreciate some help.
coreHTTP.prototype.post = (url, data) => {
return new Promise((resolve, reject) => {
fetch(url, {
method: "POST",
headers: {"content-type": "application/json"},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err));
});
}
CodePudding user response:
How bout leaving the fetch as it is? If you just want to use awaits than there's no problem with it being there.
coreHTTP.prototype.post = async (url, data) => {
const responseData = await fetch(url, {
method: "POST",
headers: {"content-type": "application/json"},
body: JSON.stringify(data)
});
const responseJson = await responseData.json();
return responseJson;
}
CodePudding user response:
You can try to remember it like this. JS uses asynchronous coding right, so we do that using promises. One way is as you see it in your question where you call for a resource(fetch in this case) and we wait for the resource modification using .then
and .catch
.
Similarly, for async/await the logic is the same except syntax is a bit different. First of all to use await inside any function we have to first define the function as async
and then you just use await ahead of any function you use inside that. You can also use try/catch to deal with errors better. Let me know if you need help understanding more.
I am new to this comments section so I dont know how to exactly attach code snippets but I will attach a screenshot for now for your reference.