我寫了一個 JavaScript 非同步函數來使用我發現的檢查拼字的 api:
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)); }
要檢查的單字會作為字串參數傳遞,例如:
let checkResult = checkWord('HOUSE'); console.log(checkResult);
我想重寫這一行:
.then(result => console.log(result))
將結果作為 JSON 物件傳回給呼叫者,但我不知道如何做到這一點。這是我嘗試過的:
.then(result => () => {return result.json();})
有人可以提出一個修復方案來讓這項工作按照我的意願進行嗎?我知道原始程式碼有效,因為原始 console.log 顯示了有效結果。但我的函數呼叫後的 console.log 僅顯示以下內容:
從函數中傳回你的承諾並刪除
async
,如下所示: