我正在开发一个函数
String.prototype.isActualWord = function() {
if ($ != undefined) {
let str = this.toLowerCase()
let res = false
const url = "https://api.wordnik.com/v4/word.json/" + str + "/definitions?limit=200&includeRelated=false&useCanonical=false&includeTags=false&api_key=_THIS_IS_CONFIDENTIAL_";
try {
$.ajax({
type: "GET",
url: url,
async: false,
success: function (data) {
res = true
},
error: function (data) {
res = false
}
})
}
catch(e) {
throw new Error(e.message)
}
return res
} else {
throw new Error("Please Include jQuery In Your Project")
}
}
这是获取代码:
let res = false
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
if(data[0] != undefined) {
res = true
}
});
你看,我想从我的项目中删除 jQuery 依赖项。我如何使用 fetch API 以异步方式实现这一点。我尝试了很多方法但没有成功。
API 的获取是异步的,因此您应该等待它再返回答案。在检查中你也应该添加 async/await:
async function testWord(word) {
let check = await word.isActualWord();
return check;
}
为了避免 cors 问题,请将带有 cors 的 init 添加到 fetch api
String.prototype.isActualWord = async function() {
let str = this.toLowerCase()
let res = false
let myHeaders = new Headers();
let myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' };
const url = "https://api.wordnik.com/v4/word.json/" + str + "/definitions?limit=200&includeRelated=false&useCanonical=false&includeTags=false&api_key=_THIS_IS_CONFIDENTIAL_";
try {
const data = await fetch(url, (myInit as RequestInit))
.then((response) => {
return response.json();
});
if(data[0] != undefined) {
res = true
}
}
catch(e) {
console.log('there was an error', e)
throw new Error(e.message)
}
return res
}
从评论看来,您希望使用 fetch 就好像它是同步的一样。
要实现此目的,请在异步函数中使用
await
关键字。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
例如,您可以遵循以下一般结构:
async function() {
await fetch(...).then(...);
return res;
}