【发布时间】:2021-06-10 17:32:26
【问题描述】:
我正在处理一个函数
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 以异步方式实现此目的。我尝试了很多方法,但都是徒劳的。
【问题讨论】:
-
你能告诉我们你尝试的获取代码吗?
-
@Scruffy 更新了我的问题。
-
如果您运行 fetch 模拟,您的要求是什么?
-
@PaulZaslavskij 当我在 promise
.then()中记录 res 变量时,它会显示更新后的值,但是当我尝试在此之外返回它时,它的值不会更新。我知道这是因为 js 的异步行为,但我不知道如何解决这个问题。 -
有两种方法可以解决它: 1. 移动代码,这将在 .then() 中使用您的响应数据。 2. 你可以使用 async/await 得到结果。比如
const myValue = await fetch('url').then((res) => res.json())。但不要忘记将父函数设为async,否则将无法使用await语句
标签: javascript fetch fetch-api