0

Hope you all are well and good. There is one thing that I want to discuss with you all and get some response. I am calling a REST API from JavaScript with POST operation using Async/Await functionality. Now, Async call is successful but I need the response that I have received from REST endpoint for further operations. So, how can I store/use the response that I received from REST endpoint (POST) when I am making asynchronous call to REST endpoint? Is there a way for me to store the response that I have received from REST endpoint for POST call?

I have used below code:

function callRESTEndpoint (requestPayload) {
   let restURI = "url";
   let head = new Headers();
   let encoded = window.btoa('username:password');
   let authorization = 'Basic ' + encoded;
   head.append('Content-Type', 'application/json');
   head.append('Authorization', authorization);
   let request = new Request(restURI, {
       method: 'POST',
       headers: head,
       mode: 'cors',
       body: JSON.stringify(requestPayload);
       credentials: 'same-origin'
   });
   let restResponse = JSON.stringify(callRESTAsynchronously(request));
   console.log('rest response: ', restResponse);
}
async function callRESTAsynchronously(requestReceived){
  try{
     const JSONResponse = await (await fetch(requestReceived)).json();
     console.log('response: ', JSONResponse);
     return JSONResponse;
  } catch(err) {
     return err;
  }
}
Mayukh Mitra
  • 39
  • 1
  • 4
  • 1
    You can just use a global variable, no? – isaacsan 123 Jun 14 '21 at 09:29
  • SO is not a discussion board. Do you have an actual problem? -> [What topics can I ask about here?](https://stackoverflow.com/help/on-topic) – Andreas Jun 14 '21 at 09:32
  • there is many way like store in variable, cookie, session storage, local storage such as https://www.w3schools.com/jsref/prop_win_localstorage.asp – Jayesh Naghera Jun 14 '21 at 09:36
  • You need to use `JSON.stringify(await callRESTAsynchronously(request));` or `callRESTAsynchronously(request).then(res => { console.log(…); });` – Bergi Jun 14 '21 at 10:22

0 Answers0