【发布时间】: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