I am using reactJs and facing a problem while working with promise in JS.
I am writing a fetch call to the API and then returning the response back to the component. In component I have written like below.
let response= {};
const promise = new Promise((resolve,reject) => {
resolve(response= fetchCallApi(request));
});
promise.then((result) =>{
console.log('result',result);
console.log('2', response);
console.log("3");
});
FetchCallApi is the function I have written in different Js , which will have the fetch method and return the response. Note: I have placed the console.log statement in this js also for the response received from the api.
In Output Console am getting result as empty object and console output for the fetch api call prints even after the console statements in promise.then function.
If i have the promise in place then it should resolve the fetchAPIcall first and print the console message from that call and then should go to promise.then and print both the console.log statements.
Can someone guide why this is happening? and how can I get the response with values and not empty object?
Note: I have even tried with async/await but no luck , can some one please share the code which will work in this case
Edit 1 : Adding the code for fetchCallApi to get clear understanding of my problem
const fetchCallApi = (request) => {
let output = {} ;
fetch('someUrl').then(resp => {
if (resp) {
output = resp.response;
console.log('1 ',output);
}
}).catch(error => {
console.log(error);
});
return output ;
}