0

I am working on a function

String.prototype.isActualWord = function() {
    if ($ != undefined) {
        let str = this.toLowerCase()
        let res = false
            
            const url = "https://api.wordnik.com/v4/word.json/" + str + "/definitions?limit=200&includeRelated=false&useCanonical=false&includeTags=false&api_key=_THIS_IS_CONFIDENTIAL_";

            try {
                $.ajax({
                    type: "GET",
                    url: url,
                    async: false,
                    success: function (data) {
                        res = true
                    },
                    error: function (data) {
                         res = false
                    }
                })
            }
            catch(e) {
                throw new Error(e.message)
            }
        return res
    } else {
        throw new Error("Please Include jQuery In Your Project")
    }
}

Here is the fetch code:

let res = false
fetch(url)
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    if(data[0] != undefined) {
        res = true
    } 
  });

you see, I want to remove the jQuery dependency from my project. how can I achieve this using the asynchronous way using fetch API. i have tried many ways but in vain.

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Can you show us the fetch code you tried? – Scruffy Jun 10 '21 at 05:45
  • @Scruffy updated my question. – Albert Logic Einstein Jun 10 '21 at 05:48
  • what you got on your request in case you running your fetch analog? – Paul Zaslavskij Jun 10 '21 at 05:48
  • @PaulZaslavskij when i log the res variable inside the promise `.then()` it shows the updated value but when I try to return it outside that, its value is not updated. and I know its because of asynchronous behaviour of js, but I don't know how to fix this. – Albert Logic Einstein Jun 10 '21 at 05:50
  • there are two ways to solve it: 1. move the code, that gonna use your response data inside of .then(). 2. you can got the result using async/await. like `const myValue = await fetch('url').then((res) => res.json())` . but don't forget to make parent function `async`, otherwise it will be impossible to use await statement – Paul Zaslavskij Jun 10 '21 at 05:54
  • @PaulZaslavskij i tried this: `res = await fetch(url).then((res) => res.json()).then(data => { if(data[0] != undefined) { return true } else { return false } })` and it returns a pending promise – Albert Logic Einstein Jun 10 '21 at 05:59
  • Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Evert Jun 10 '21 at 07:32

2 Answers2

1

The fetching of the API is asynchronous so you should wait for it before returning the answer. In the checking you should add async/await too:

async function testWord(word) {
    let check = await word.isActualWord();
    return check;
}

And to avoid cors issues add init with cors to the fetch api

String.prototype.isActualWord = async function() {
  let str = this.toLowerCase()
  let res = false
  let myHeaders = new Headers();
  let myInit = { method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };
      
  const url = "https://api.wordnik.com/v4/word.json/" + str + "/definitions?limit=200&includeRelated=false&useCanonical=false&includeTags=false&api_key=_THIS_IS_CONFIDENTIAL_";

  try {
    const data = await fetch(url, (myInit as RequestInit))
    .then((response) => {
      return response.json();
    });
      if(data[0] != undefined) {
          res = true
      }
  }
  catch(e) {
    console.log('there was an error', e)
      throw new Error(e.message)
      }
  return res
}
Dani
  • 745
  • 7
  • 12
0

It seems from the comments you're looking to use fetch as though it were synchronous.

To achieve this, use the await keyword inside an async function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

For example, you might follow this general structure:

async function() {
  await fetch(...).then(...);
  return res;
}
Scruffy
  • 580
  • 8
  • 23