I need help because I couldn’t use a separate function to generate the token – it gives out a promise, not a value. I was told that a value can only be used inside a function.
For each request, I generate a new token in the first request and then pass that token into the second request.
I tried making a separate function to generate the token, but fetch returns a promise.
As a result, I made such a big function and it works. Is there a way to make a separate function for the first request and pass the result to the second request?
The first token generation function is required frequently, while the second request is always different.
fetch('/api/token', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ 'id': '5' }), }) .then(response => response.json()) .then(result => { fetch('/api/reviews', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + result.token, }, body: JSON.stringify({ 'limit': 10 }), }) .then(response => response.json()) .then(result => { this.setState({ data: result.data }); }) })
Advertisement
Answer
create a function that return promise
async function getToken() { return await fetch('/api/token', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ 'id': '5' }), }) .then(response => response.json()) .then(result => { return Promise.resolve(result.token); }).catch(error => { return Promise.reject(error); }) } async function getReview() { const token = await getToken().then(token => { return token }).catch(error => { //handle error }); fetch('/api/reviews', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token, }, body: JSON.stringify({ 'limit': 10 }), }) .then(response => response.json()) .then(result => { this.setState({ data: result.data }); }) }
i did not test this code but you get the idea
i will test and update my answer asap