首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正确的异步/等待功能

正确的异步/等待功能
EN

Stack Overflow用户
提问于 2020-10-20 12:21:27
回答 1查看 43关注 0票数 0

我正在尝试运行一个机器人,刮亚马逊(使用亚马逊伙伴)的某些产品(使用阵列的ASIN),并检查价格。如果价格不是0,它应该发送不一致的消息。我目前将它设置为每30秒运行一次,并且运行正常,但有时似乎每个元素都没有等待前一个元素在forEach循环中获得响应,并且我的函数似乎不正确(我仍然在尝试正确地理解异步/等待函数)。

有没有更好的方法来运行它,让每个元素在移动到下一个元素之前等待前一个元素被抓取,然后在30秒后再次运行循环?

代码语言:javascript
复制
(function() {
  var c = 0;
  var timeout = setInterval(function() {
      const checkStock = (async () => {
        config.items.itemGroup.forEach(element => {
          console.log('Checking stock on ' + element)
        try {
          const product_by_asin = await amazonScraper.asin({ asin: element });
          console.log(product_by_asin)
          const price = product_by_asin.result[0].price.current_price
          const symbol = product_by_asin.result[0].price.symbol
          const asin = product_by_asin.result[0].asin
          const title = product_by_asin.result[0].title
          const url = product_by_asin.result[0].url
          const image = product_by_asin.result[0].main_image

          if (price != 0) {
            const inStockResponse = {
              color: 0x008000,
              title: title + ' is in stock!',
              url: url,
              author: {
                name: config.botName,
                icon_url: config.botImg,
                url: config.botUrl
              },
              description: '<@767456705306165298>, click the tite to go purchase!\n\n' +
              'Price: ' + symbol + price,
              thumbnail: {
                url: image
              },
              timestamp: new Date()
              }
        
            message.channel.send({embed: inStockResponse });
            console.log(title + ' (' + asin + ') IS available!')
          } else {
            console.log(title + ' (' + asin + ') IS NOT available!')
          }
        } catch (error) {
          console.log(error);
        }
      });
      checkStock()
    });
    console.log('Counter: ' + c)
    c++;
  }, 30000);
})();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-20 12:33:06

您可以使用for...of循环,它可以等待每次迭代完成:

代码语言:javascript
复制
async function checkItems(items) {
  // Check all items, wait for each to complete.
  for (const item of items) {
    try {
      const product_by_asin = await amazonScraper.asin({ asin: item });
      console.log(product_by_asin);
      const price = product_by_asin.result[0].price.current_price;
      const symbol = product_by_asin.result[0].price.symbol;
      const asin = product_by_asin.result[0].asin;
      const title = product_by_asin.result[0].title;
      const url = product_by_asin.result[0].url;
      const image = product_by_asin.result[0].main_image;

      if (price != 0) {
        const inStockResponse = {
          color: 0x008000,
          title: title + " is in stock!",
          url: url,
          author: {
            name: config.botName,
            icon_url: config.botImg,
            url: config.botUrl,
          },
          description:
            "<@767456705306165298>, click the tite to go purchase!\n\n" +
            "Price: " +
            symbol +
            price,
          thumbnail: {
            url: image,
          },
          timestamp: new Date(),
        };

        // NOTE: you might want to wait for this too, the error
        // currently isn't being handled like this either.
        message.channel.send({ embed: inStockResponse });
        console.log(title + " (" + asin + ") IS available!");
      } else {
        console.log(title + " (" + asin + ") IS NOT available!");
      }
    } catch (err) {
      console.log(err);
    }
  }

  // Wait 30s and check again.
  setTimeout(() => checkItems(items), 30000);
}

checkItems(config.items.itemGroup);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64438428

复制
相关文章

相似问题

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