1

I have a simple function:

var result = '';
var url ='http://someurl.com/?action=perform-action';

(async function() {
    let a = await fetch(url)
    result = await a.text();
})()

console.log(result)

I'm trying to put the result into variable but it returns nothing. My function simply checks if an email entered into an input exists in our database. Result is "Exists" or "OK". Works fine when I send it to the console but I need the result to perform other actions. If I save it to result it shows nothing.

3

Eventually your result variable will include the response from the fetch, but you're displaying the result before the fetch has completed its call.

Let's annotate the order:

var result = ''; // 1
var url ='http://someurl.com/?action=perform-action'; // 2

(async function() {
    let a = await fetch(url); // 5
    result = await a.text(); // 6
})() // 3

console.log(result); // 4

If you moved your console.log call into the async function after the result is set you'd achieve your goal, like so:

var result = '';
var url ='http://someurl.com/?action=perform-action';

(async function() {
    let a = await fetch(url)
    result = await a.text();
    console.log(result);
})()

If the goal is to do something with that result outside the async call -- like somewhere else in your platform -- you'd need to observe the changes, or call an 'after result' function (which could be an injected callback.)

Here's a working example:

var result = '';
var url ='https://jsonplaceholder.typicode.com/todos/1';

(async function() {
    const a = await fetch(url);
    result = await a.text();
    console.log(result);
})()

  • Hi Alex, thank you for responding. I have tried your example and this works, however I need to do something with the result either inside or outside the async call. Example: if(result=='EXISTS'){//Do something} This does not work however. Any further help or examples? – Benzine Mar 12 at 6:05
  • Thanks Alex, I misspelt the result, EXISTS instead of EXIST. Also created a callback function within the aysnc call and it works now. – Benzine Mar 12 at 6:24

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.