I have this function in my context provider I want it to return a promise so that I can access the returned data from axios
const sendRquest =(service,data,method,url)=>{
let base = api.find(item => item.name ===service )
let config = {
method: method,
url: `${base.url}/${url}`,
headers: {
'x-clientId': clientId,
'Content-Type': 'application/json',
},
data: data
};
axios(config)
.then(function (res) {
return res
})
.catch(function (error) {
return error
});
}
And the result I'm looking for is to write such code in every other component whenever I needed
sendRquest('usermanagement',data,'post','foo/bar').then(res=>console.log(res.data)).catch(err=>console.log(err))
You have to return the promise.
Something like
const sendRquest =(service,data,method,url)=>{
let base = api.find(item => item.name ===service )
let config = {
method: method,
url: `${base.url}/${url}`,
headers: {
'x-clientId': clientId,
'Content-Type': 'application/json',
},
data: data
};
return axios(config)
.then(function (res) {
return res
})
.catch(function (error) {
return error
});
}
Be careful tho because you are "swallowing" errors by using .catch
like this. The promise returned by sendRquest
will never "fail" (reject) but will succeed (resolve) with either data or error payloads.
the complete answer is like this
may help you all
const sendRquest =(service,data,method,url)=>{
let base = api.find(item => item.name ===service )
let config = {
method: method,
url: `${base.url}/${url}`,
headers: {
'x-clientId': clientId,
'Content-Type': 'application/json',
'Authorization': token
},
data: data
};
return axios(config)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.