0

Below is my JS Method

function test(key, language) {
        var uri = '/Resources/ValidationMessages.json';
        fetch(uri).then(response => {
            return response.json();
        }).then(data => {
            console.log('Inside Function - ' + data[key]);
            return data[key];
        }).catch(err => {
            console.log(' Error ');
        });
    }

And after calling this method as

var v = test('spnrequiredRegisterEmail');
console.log('Outside Function - ' + v);

Inside the function it print value but Outside Function statement is always undefined.

The solution that I am trying to achieve is that I have to set some text in n number of span as inner text, which will come through this function call after passing the respective key, but every span displays undefined as inner text

It won't wait for a method to finish , so how can I solve this issue?

Dominik Matis
  • 2,086
  • 10
  • 15
Saurabh
  • 1,505
  • 6
  • 20
  • 37

1 Answers1

-1

Try using async / await

async function test(key, language) {
    try {
        var uri = '/Resources/ValidationMessages.json';
        var resp = await fetch(uri);
        var data = resp.json();
        console.log('Inside Function - ' + data[key]);
        return data[key];    
    catch(err) {
        console.log(err);
    }
}
Dominik Matis
  • 2,086
  • 10
  • 15