0

I have a reactJS application where I am trying to validate some user input against a database value. The database is stored on AWS so I am using a fetch to a Web API that I wrote. This is the code that I am executing:

                passString = "003" + newValue;
                console.log("call function with ", passString);
                var returnedValue = mqRequest(passString);
                console.log("return from fetch with ", returnedValue);
                if (returnedValue != newValue) {
                    localPlanID.message = "The Plan ID you entered was not found on our system";
                    localPlanID.css = "textbox4Bytes input-box-error";
                }

The value of the variable newValue is VSTA

The code will call a function called mqRequest that is in a separate file. I include this by using this line of code:

import {mqRequest} from '../functions/commonFunctions.js';

The code of the function looks like this:

export function mqRequest (passedData) {

//var url = "https://webaccuapi-dev.accurecord-direct.com/api/homepage?mqRequest=" + passedData;
var url = "http://webaccuapi-dev.accurecord-direct.com/api/homepage?mqRequest=" + passedData;
const options = { method: 'GET' };
var returnString = "";

fetch(url, options)
.then(function(response) {
    return response.json();
})
.then(function(myJson) {
    if (myJson == undefined) 
    {
        returnString = "fetch failed";
    } 
    else 
    { 
        returnString = myJson[0].return_response;
        console.log("from function, myJson[0] = ", myJson[0]);
    }
}); 
 console.log("from function, after fetch, returnString = ", returnString);
return returnString;

}

When I execute the code, this is what I see in the console.log:

call function with  003VSTA 
from function, after fetch, returnString =  
return from fetch with  
from function, myJson[0] =  {return_response: "VSTA", return_code: "0", return_plan_name: "N/A", return_menu_string: "N/A"}

So, it appears that I am calling the function and passing it 003VSTA. The function picks up this value, builds the url variable, and executes the fetch. The fetch returns myJson[0].return_response with a value of VSTA which is correct!

The problem that I am having is, I think, a timing issue. I believe the function is called but the code is continuing to execute even though the function and fetch have not finished executing. How do I get the code to wait for a value to be returned by the function before continuing?

Thanks.

Jonathan Small
  • 1,027
  • 3
  • 18
  • 40
  • Sorry dude TLDR – Adam Dec 05 '18 at 21:35
  • In a netshell, how do I call a function which contains a fetch to an external data source and have the code wait for the returned data instead of continuing with the flow of the code without the returned data from the function. – Jonathan Small Dec 05 '18 at 21:40
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – skyboyer Dec 05 '18 at 21:45

1 Answers1

1

The timing issue is due to the fact the fetch call is asynchronous.

To resolve your timing issue, there are a couple of approaches. A popular one is to use Promises for the job. Here's how:

First, you need to tweak the "mqRequest" function:

export function mqRequest (passedData) {
  // ...

  // Step 1: Instead of returning a String, return a Promise.
  return new Promise((resolve, reject) => {
    fetch(url, options)
      .then(function(response) {
          return response.json();
      })
      .then(function(myJson) {
          if (myJson == undefined) {
            returnString = "fetch failed";
          } else { 
            returnString = myJson[0].return_response;
            console.log("from function, myJson[0] = ", myJson[0]);
          }

          // Step 2: resolve the Promise with the String
          resolve(returnString);
      });
  });
}

Then, call it like you would call a Promise:

passString = "003" + newValue;
console.log("call function with ", passString);
mqRequest(passString).then(function(returnedValue){
  console.log("return from fetch with ", returnedValue);
  if (returnedValue != newValue) {
    localPlanID.message = "The Plan ID you entered was not found on our system";
    localPlanID.css = "textbox4Bytes input-box-error";
  }
});

This way, the mqRequest function call will wait for the returned data instead of continuing with the flow of the code without the returned data.

And now your logs should execute as expected.

Kaloyan Kosev
  • 12,483
  • 8
  • 59
  • 90