如何从 jQuery 转换为获取 API

How to convert from jQuery to fetch API

我正在处理一个函数

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 来实现这一点。我试了很多方法都没有用

从评论看来,您希望使用 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;
}

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
}