0

With the above function, I want to read a term from a dictionary which is written in a JSON file.

function readterm(index){
    var s="";

    return new Promise( (resolve, reject) => {
    
    fetch('JsonFiles/vocabulary.json')
        .then(response => response.json())
        .then(data => {
            s = data.vocabulary.entry[index].term;
            console.log(s);
            resolve(s);
    }).catch(reject);
});
}

and I call this function, by using the above code:

s1= readterm(5);
console.log(s);

My problem is that when I call this function, the result a have is that:

Promise {<pending>}__proto__: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: "apple"

How can I take the promise result and set it to the variable s1, so in this example, the returned value will be s1 = "apple";

  • 2
    Please see the answers on this question: [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) or on one of the many other questions on Stack Overflow asking the same thing. There is also no need to wrap your fetch in another Promise, because fetch already returns a promise. – Zac Anger Jan 13 '21 at 18:13
  • You can't. You can pass the Promise around, and call `.then` on it to access the value. – Jared Smith Jan 13 '21 at 18:13
  • I tried to solve the problem according to answers for similar problems but still I can't figure out the solution. I am new to Javascript and it seems very difficult to me. Could you please indicate an example? – Giota Panagiota Jan 14 '21 at 14:32

0 Answers0