首页 > 解决方案 > 请求 API 并等待答复

问题描述

如果我没有得到两个可能的响应“是”或“否”之一,我需要将 GET 请求发送username=alison&date=2021到文件并每 200 毫秒发送一次请求,重新发送请求需要得到正确的答案,没有空白且没有错误。file.php

如果得到“是”“否”做功能。收到响应时,执行不同的操作

  1. 收到yes后的功能
  2. 没有收到后的功能

标签: javascript

解决方案


我不是 100% 确定您在这里要求什么,但这是我的方法,基于我自己使用来自 GitHub 的 API 的调用对您的问题的解释。我们正在使用 fetch 来提取数据。我们的 .then 是我们的决心,我们的 .catch 是我们的拒绝。

const url = 'https://api.github.com/users'

const callApi = function(fetchUrl){
    fetchUrl = url
    fetch(fetchUrl)
        .then(response=>{
            return response.json(); // Turn data to JSON
        })
        .then(data=>{ // If it was successful, this below will run
            console.log(data) // Do whatever you want with the data from the API here
        })
        .catch(err=>{ // If it was unsuccessful, this below will run
            console.log(err); // Console log the error
            setTimeout(callApi(url), 200); //If it failed, try again in 200ms
        })
}

callApi(url) // Initial function call

需要注意的一些事项:如果您使用的 API 限制了您在一天/一个月内可以进行的调用次数,那么这将很快耗尽那些分配的请求。


推荐阅读