javascript - 请求 API 并等待答复
问题描述
如果我没有得到两个可能的响应“是”或“否”之一,我需要将 GET 请求发送username=alison&date=2021
到文件并每 200 毫秒发送一次请求,重新发送请求需要得到正确的答案,没有空白且没有错误。file.php
如果得到“是”“否”做功能。收到响应时,执行不同的操作
- 收到yes后的功能
- 没有收到后的功能
解决方案
我不是 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 限制了您在一天/一个月内可以进行的调用次数,那么这将很快耗尽那些分配的请求。
推荐阅读
- django - Django REST Serializer 使用错误的模型进行序列化
- python - python文件写入程序运行时如何更新桌面上的文件大小
- javascript - 使用 d3.js 更新表数据
- c# - C#捕获从不在进程中的函数返回的异常?
- r - 如何设置仅在输入 3 时才显示集合向量的函数?
- javascript - 如果 URI 没有改变,例如在单页应用程序上,如何检测用户是否在新页面上?
- angular - Angular Kendo UI 全局访问
- php - 内连接循环通过
- git - 如何 git rebase 从另一个分支直接到 master 分支?
- javascript - 受控数字比例映射