首页 > 解决方案 > 在 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 循环似乎继续执行,而不是等待用户输入。谁能帮助我用正确的方法来实现这个想法?

标签: javascriptnode.jsasynchronouspromiseaxios

解决方案


推荐阅读