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:
3
Answers
Return your promise from the function and remove
async
like this: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:
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.
You can use simply await
and the function call would look like