How to return JSON result from API call
P粉916760429
P粉916760429 2024-01-10 17:08:12
0
1
493

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粉916760429
P粉916760429

reply all(1)
P粉966335669

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));
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template