【问题标题】:recursive promises won't execute递归承诺不会执行
【发布时间】:2018-01-28 00:20:13
【问题描述】:

好吧,在一段(微不足道的,我已经移动了实际负载并用时间替​​换它)的一段代码中,我希望承诺递归发生:

const all_related = [];
const createSub = async function(maxNum, depth) {
  if (depth > 0) {
    const n = 0;
    console.log(`depth: ${depth}`);
    const id = depth*maxNum +  n + 1;
    console.log(`id: ${id}`);
    try {
      const promise = new Promise(resolve => {
        setTimeout(resolve, 10, this);
      });
      await promise;
      all_related.push(id);
      console.log('after');
    } catch (err) {
      console.log(err);
    }
    createSub(maxNum, depth - 1);
  }
};
try {
  await createSub(1, 2);
} catch(err) {
  console.log(err);
}
console.log(all_related);

函数应该很清楚:它基本上“基于”先前的承诺创建承诺,直到用完depth。

我期望的最终数组 (all_related) 是 [3, 3]。但此外,我希望日志是这样的:

depth: 2
id: 3
after
depth: 1
id: 2
after
[ 3, 2 ]

但是我看到的日志是:

depth: 2
id: 3
after
depth: 1
id: 2
[ 3 ]

也根本没有错误记录,也没有任何报告。 - 所以这表明第二个“深度”承诺根本没有执行。 - 为什么是这样?该函数已执行(我看到id: 2),它只是在第二个承诺时完全退出。

哦,我该如何解决这个问题?

【问题讨论】:

  • 您不需要将“递归”调用设为await createSub(...)吗?

标签: javascript recursion promise


【解决方案1】:

您没有在等待递归调用,因此原始调用在该调用之前完成。

await createSub(maxNum, depth - 1);

这是一个演示:

const all_related = [];
const createSub = async function(maxNum, depth) {
  if (depth > 0) {
    const n = 0;
    console.log(`depth: ${depth}`);
    const id = depth * maxNum + n + 1;
    console.log(`id: ${id}`);
    try {
      const promise = new Promise(resolve => {
        setTimeout(resolve, 10, this);
      });
      await promise;
      all_related.push(id);
      console.log('after');
    } catch (err) {
      console.log(err);
    }
    await createSub(maxNum, depth - 1);
  }
};
async function test() {
  try {
    await createSub(1, 2);
  } catch (err) {
    console.log(err);
  }
}

test();

顺便说一句,您的调用堆栈会随着这种方法继续增长,因此您会失去异步代码的一些好处。没什么大不了的,但要记住一些事情。

【讨论】:

  • 我会记住这个提示——尽管这段代码基本上是一个集成测试的设置(填充一个数据库并在它们之间创建链接),所以并不意味着要优化。
猜你喜欢
  • 2020-07-22
  • 2014-02-04
  • 1970-01-01
  • 2013-12-14
  • 2018-10-11
  • 2018-05-29
  • 2021-11-21
  • 2016-06-13
  • 2017-11-01
相关资源
最近更新 更多