javascript - 在 NODE JS 中使用 Axios 在无限循环内调用异步 API
问题描述
首先让我说我是异步 JavaScript 的初学者,我花了很长时间才理解这个概念。
现在,谈到手头的情况。我想编写一个代码,该代码将使用 OCR API 自动检测包含多个屏幕截图的文件夹中的文本,其文档可在此处找到:https ://ocr.space/OCRAPI
OCR 使用两个引擎,可以产生不同的结果。代码应使用指定的默认引擎运行并显示内容。如果结果令人满意,用户可以选择继续下一个屏幕截图,或者使用不同的引擎发出另一个 api 请求。
我尝试使用无限的while循环来实现这一点:
const fs = require("fs")
const imageToBase64 = require("image-to-base64")
const apikey = "helloworld"
let engine = 1
fs.promises
.readdir("./screenshots")
.then((files) => {
for (const file of files) {
while (true) {
console.log("Making an API Request")
imageToBase64("./screenshots/" + file)
.then((res) => {
const form = new FormData()
form.append("base64Image", "data:image/jpeg;base64," + res)
form.append("OCREngine", engine)
axios
.post("https://api.ocr.space/parse/image", form, {
headers: { apikey, ...form.getHeaders() },
})
.then((response) => {
console.log(response.data.ParsedResults[0].ParsedText)
/*Code to ask the user whether the result is satisfactory or not.
if yes, break out of the while loop, otherwise change the engine and make the request again*/
engine = 2
})
.catch((error) => console.log(error))
})
.catch((error) => console.log(error))
}
}
})
.catch((error) => console.log(error))
无限 while 循环似乎继续执行,而不是等待用户输入。谁能帮助我用正确的方法来实现这个想法?
解决方案
推荐阅读
- python - clean_data 中的有效 POST 参数值为空
- python - 带有条件语句的 Pandas Loc
- python - 计算相似向量的频率
- laravel - 如何在 laravel eloquent 中从产品表和项目表中检索交货表的所有数据
- algorithm - 检测和修复信号中的错误/尖峰的算法
- java - 将 Vespa 缩放为 500 QPS 以进行搜索
- vue.js - NuxtJS,VueX - 如何最大限度地减少代码
- javascript - 键入 Redux Reactjs 时 TextField 失去焦点
- video - 根据 Manifest 属性和持续时间计算视频大小
- javascript - 你如何在 Golang 中创建前端?和其他问题