search

Home  >  Q&A  >  body text

How to return JSON result from API call

I wrote a JavaScript async function to use the spell-checking API I found:

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 check is passed as a string parameter, for example:

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

I want to rewrite this line:

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

Return the result to the caller as a JSON object, but I don't know how to do this. Here's what I've tried:

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

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

P粉916760429P粉916760429317 days ago460

reply all(1)I'll reply

  • P粉966335669

    P粉9663356692024-01-11 16:22:09

    Return your promise from the function and remove the 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));
    }

    reply
    0
  • Cancelreply