首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >一次又一次地调用异步函数,直到Node的预期结果

一次又一次地调用异步函数,直到Node的预期结果
EN

Stack Overflow用户
提问于 2020-02-17 02:22:00
回答 1查看 526关注 0票数 0

假设我有4项任务

一个网站的截图(使用一些API service)

  • Download,截图到您的本地hardDrive

  • Upload,从本地hardDrive到Google

  • 的屏幕截图,使用GC检测屏幕截图

上的文本)。

如果任务#4的结果等于-1,这意味着我没有找到我正在寻找的东西,所以我需要再次这样做,直到结果不等于-1 (这可能意味着我找到了我需要的东西)。

下面是一些代码:

代码语言:javascript
运行
复制
const screenshot = require("./thum/takeScreenshot");
const googleVisionAPI = require("./gc-vision-api/findTextInButton");
const matchURL = /^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/;
const UploadToGcBucket = require("./gc-storage/saveScreenshot");
const downloadImage = require("./downloadFile");

// let's wait for the bucket to replicate before searching text
function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const workHard = async () => {
  // 1. Take a screenshot
  const takeAscreenShot = async () => {
    let scShotTaken = await `https:${screenshot.thumURL}`;
    console.log("screenshot captured!!! ", scShotTaken);
    return scShotTaken;
  };

  //  2. Download it to local hard-drive
  const downloadScreenshot = async url => {
    let download = await downloadImage.downloadImage(url);
    return download;
  };

  // 3. Upload it to Google Cloud Bucket
  const uploadToGCBucket = async () => {
    let upload = await UploadToGcBucket.UploadToGcBucket();
    return upload;
  };

  // 4. Check if the appointment's button is present
  const checkMagicButton = async () => {
    // wait a little bit for replication
    await timeout(5000);

    let searchAppointment = await googleVisionAPI.findMagicButton(
      `some_picture_in_a_cloud_bucket.jpg`
    );
    return searchAppointment;
  };

  takeAscreenShot()
    .then(pic => {
      // Verify if it looks like a URL
      let verifyURL = matchURL.test(pic);

      if (!verifyURL) {
        return "The screenshot doesn't look like a valid URL, check the Thumb API";
      }

      downloadScreenshot(pic)
        .then(() => {
          uploadToGCBucket()
            .then(() => {
              checkMagicButton()
                .then(button => {
                  if (button === -1) {
                    throw new Error();
                  }
                })
                .catch(makeCatch("AI finding button ERROR"));
            })
            .catch(makeCatch("Uploading to GC Bucket ERROR"));
        })
        .catch(makeCatch("Downloading ERROR"));
    })
    .catch(makeCatch("ScreenShot ERROR"));
};

const makeCatch = msg => err => {
  console.log("Problem with " + msg, err);
  throw new Error(); // this is important- this rejects the Promise, so it stops the hardWork
};

const tryWork = () => {
  workHard().catch(error => {
    setInterval(tryWork, 5000);
  });
};

tryWork();

so...how,如果我找不到我需要的东西,我会再次调用HardWork(),如果我找不到所需的东西,那么在5分钟内调用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-17 02:35:59

您已经在使用async函数了,而且一切看起来都是基于承诺的,所以您可以在其中创建hardWork async,然后将每个承诺都放在其中。如果最终任务失败,拒绝。在hardWork的调用方中,如果承诺最终被拒绝,设置一个超时在5分钟内再次调用它,否则您就完成了:

代码语言:javascript
运行
复制
const hardWork = async () => {
  // I assume this next line was psuedo-code for an API call or something
  await `https:${screenshot.thumURL}`;

  const image = await downloadImage.downloadImage();
  await UploadToGcBucket.UploadToGcBucket(image);
  await timeout(5000);
  const button = await googleVisionAPI.findMagicButton(`some_screenshot.jpg`);
  if (button === -1) {
    throw new Error();
  }
  // success
};

const tryWork = () => {
  hardWork()
    .catch((error) => {
      setTimeout(tryWork, 5 * 60 * 1000); // 5 minutes
    });
};
tryWork();

如果您需要针对不同可能的错误提供不同的错误消息,我将创建一个更高级的函数,您可以将该函数传递到记录消息的.catch中,以保持代码的干净度:

代码语言:javascript
运行
复制
const makeCatch = msg => (err) => {
  console.log('Problem with ' + msg, err);
  throw new Error(); // this is important- this rejects the Promise, so it stops the hardWork
};

// ...

await downloadImage.downloadImage()
  .catch(makeCatch('downloadImage'));
await UploadToGcBucket.UploadToGcBucket(image)
  .catch(makeCatch('upload to gc'));
await timeout(5000);
const button = await googleVisionAPI.findMagicButton(`some_screenshot.jpg`)
  .catch(makeCatch('findButton'));

现场片段:

代码语言:javascript
运行
复制
// dummied up API calls below...
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
const downloadImage = () => new Promise(resolve => setTimeout(resolve, 200));
const uploadToGcBucket = () => new Promise(resolve => setTimeout(resolve, 200));
// the below function will resolve to -1 70% of the time, and to 0 30% of the time
const findMagicButton = () => new Promise(resolve => setTimeout(resolve, 200, Math.floor(Math.random() - 0.7)));
// dummied up API calls above...

const hardWork = async () => {
  const image = await downloadImage();
  await uploadToGcBucket(image);
  await timeout(500);
  const button = await findMagicButton(`some_screenshot.jpg`);
  if (button === -1) {
    throw new Error();
  }
  console.log('success');
};

const tryWork = () => {
  hardWork()
    .catch((error) => {
      console.log('failure, retry');
      setTimeout(tryWork, 2 * 1000); // 2 seconds
    });
};
console.log('start');
tryWork();

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60255150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档