skip to Main Content

I have written a JavaScript async function to use an api I found that checks spelling:

async function checkWord(word) {
  var myHeaders = new Headers();
  myHeaders.append("apikey", "My api key");
  var requestOptions = {
    method: 'GET',
    redirect: 'follow',
    headers: myHeaders
  };
  fetch(`https://api.apilayer.com/spell/spellchecker?q=${word}`, requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
  }

The single word to be checked is passed as a string argument, for example:

let checkResult = checkWord('HOUSE');
console.log(checkResult);

I want to rewrite this line:

  .then(result => console.log(result))

to return the result to the caller as a JSON object but I can’t figure out how to do that. Here is what I tried:

 .then(result => () => {return result.json();})

Can someone suggest a fix to make this work as I want? I know the original code worked because the original console.log shows a valid result. But the console.log after my function call only shows this:

enter image description here

3

Answers


  1. Return your promise from the function and remove async like this:

    function checkWord(word) {
      var myHeaders = new Headers();
      myHeaders.append("apikey", "My api key");
      var requestOptions = {
        method: 'GET',
        redirect: 'follow',
        headers: myHeaders
      };
      return fetch(`https://api.apilayer.com/spell/spellchecker?q=${word}`, requestOptions)
      .then(response => response.text())
      .then(result => result.json())
      .catch(error => console.log('error', error));
    }
    Login or Signup to reply.
  2. To return the JSON result from your checkWord function, you need to modify the function slightly and use the async/await syntax. The fetch API returns a Promise, and you can await the response and then parse it as JSON using the .json() method. Here’s how you can do it:

    async function checkWord(word) {
      var myHeaders = new Headers();
      myHeaders.append("apikey", "My api key");
      var requestOptions = {
        method: 'GET',
        redirect: 'follow',
        headers: myHeaders
      };
    
      try {
        const response = await fetch(`https://api.apilayer.com/spell/spellchecker?q=${word}`, requestOptions);
        const result = await response.json();
        return result; // This will be a JSON object
      } catch (error) {
        console.log('error', error);
        return null; // Handle the error gracefully, you can also throw an error if needed
      }
    }
    
    // Usage
    async function someFunction() {
      try {
        let checkResult = await checkWord('HOUSE');
        console.log(checkResult);
      } catch (error) {
        console.log('Error occurred:', error);
      }
    }
    
    someFunction();
    

    By using async/await, you can wait for the Promise to be resolved and directly work with the parsed JSON data within the checkWord function and also within the calling function (someFunction in this case). Remember that when using async/await, the function should always be called within an async context, which is why someFunction() is defined as async.

    The checkWord function will now return a JSON object that you can handle in your code as needed. If there’s an error during the API call, it will be caught by the try…catch block, and you can handle it gracefully.

    Login or Signup to reply.
  3. You can use simply await

    async function checkWord(word) {
      const myHeaders = new Headers();
      myHeaders.append('apikey', 'My api key');
      const requestOptions = {
        method: 'GET',
        redirect: 'follow',
        headers: myHeaders
      };
      try {
        const response = await fetch(`https://api.apilayer.com/spell/spellchecker?q=${word}`, requestOptions);
        const result = await response.json();
        return result;
      } catch (error) {
        console.log('error', error);
      }
    }
    

    and the function call would look like

    const checkResult = await checkWord(word);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search