Adison Masih
Adison Masih

Reputation: 824

How to convert from jQuery to fetch API

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.

Upvotes: 0

Views: 767

Answers (2)

Dani
Dani

Reputation: 895

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
}

Upvotes: 1

Scruffy
Scruffy

Reputation: 580

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;
}

Upvotes: 0

Related Questions