It is quite useful to create our own callApi method in the application. In this article, I will talk about three ways to implement it with promise, async/await.
First of all, there are some things to be clarified about async/await and promise:
const callApi = (url, params) => {
return fetch(url, params).then(res => {
// response instances are returned when fetch() promises are resolved.
return res.json() // the value returned is resolved
})
}
// to use
callApi(url, params).then(res => {
console.log(res)
})
const callApi = (url, params) => {
return new Promise((resolve, reject) => {
fetch(url, params)
.then(res => {
return res.json()
})
.then(res => {
resolve(res) // the value resolved will be returned by the promise
})
})
}
// to use
callApi(url, params).then(res => {
console.log(res)
})
async function callApi(url, params) {
const res = await fetch(url, params)
return res.json() // async function returns a promise which will be resolved with the returned value
}
// to use:
;(async () => {
const res = await callApi2(url, params)
console.log("res", res)
})()