【问题标题】:NodeJS Loop not awaiting for .then as wellNodeJS Loop 也不在等待 .then
【发布时间】:2020-02-28 01:31:34
【问题描述】:

目前我的异步函数中有一个循环,如下所示:

async function getInfo(){

  for(var i=0; i < 550; i++){

      await client.decodeRecaptchaV2({
        googlekey: 'xxx',
        pageurl: 'website.com'
      }).then(async function(response) {

        await enter(i, response);

      });
  }

}

我的问题是循环等待 decodeRecaptchaV2 函数完成,然后重复自身而不等待 then 语句中的 enter 函数完成。

我需要循环来运行 decodeRecaptchaV2 函数,然后是 enter 函数,然后重复循环。

感谢任何帮助!

【问题讨论】:

  • a) 我不会使用.then() 模式,如果async/await 可用,特别是不要混合使用它们。 b) enter() 是您编码的还是您确定它实际上支持 Promise 模式?
  • @Sirko enter() 是我自己编码的,是的。我看不到 .then() 模式的另一种解决方法,因为它被 npm 库使用
  • async/await 基本上只是使用then() 的语法糖。所以你应该可以在这里使用它。如果enter()也是你的,你能添加它的来源吗?很可能问题出在该函数上,因为当前给定的代码看起来不错。
  • enter() 是否返回承诺?如果是这样,你可以做return enter(i, response)。如果没有,那么这就是你的问题,因为它需要它才能工作。
  • 你可以告诉我们enter函数的作用。

标签: node.js for-loop asynchronous async-await


【解决方案1】:
let req = 550
req.foreach(async element => {

await client.decodeRecaptchaV2({
        googlekey: 'xxx',
        pageurl: 'website.com'
      }).then(async function(response) {

        await enter(element , response);

      });
});

【讨论】:

    【解决方案2】:

    不要混合异步模式。如果你想要 asyncawait 的好处,它们可以自动处理 Promise 数据的过程,那么不要同时使用显式 Promise.then():

    async function getInfo() {
      for(let i=0; i < 550; i++){
        const response = await client.decodeRecaptchaV2({
          googlekey: `google-key-value`,
          pageurl: `example.com`
        });
    
        const e = await enter(i, response);
    
        // maybe with error generation, because I have no idea what your code does:
        if (!e) {
          throw new Error(`...`);
        }
      }
    }
    

    为什么你会等待 550 次连续解码尝试作为“getInfo”的一部分,虽然......不知道,这看起来很奇怪,并暗示了一个更大的问题;但是,如果您只想知道如何解决发布的问题,就是这样。

    【讨论】:

    • 这不是解决方案。如果enter() 正确返回了一个与其异步操作相关联的promise,那么OP 的代码就可以正常工作。所以,这实际上并不能解决任何问题。
    • 它确实解决了一个问题,即模式混合,如果你说的是真的(它可能是真的),那么现在调试起来要容易得多。即使它不能解决根本问题,但它肯定解决了很多问题。
    【解决方案3】:
    you should not write code in node js if this is the case. two await 550 times???
    

    如果你需要在内部使用 await,请使用 for...of 循环。

    {
        var a = await b();
        var c = await d(a);
    }
    

    您所写的内容看起来像是 promise 和 async await 的组合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多