【发布时间】:2017-11-23 03:41:07
【问题描述】:
我正在尝试在 node.js 中进行一些堆栈操作 基本上我试图让下面的代码工作。问题是弹出发生在推送之前,我得到“空堆栈”错误。
const stack = new stack;
findAllOfA()
.then(allA => { //first then
return Promise.all(allA.map(A => {
stack.push(a);
});
})
.then(() => { //second then
var topA = stack.pop();
//Do some things with topA
}
我想我应该从 map 的函数中返回一些东西,但我不知道要返回什么来确保第一个 then 在调用第二个 then 之前被填充。
这是伪代码(真实代码相当混乱) 真正的代码来了(小心)
const catStack = new dataStructures.Stack();
let layer = 0;
//Generic while promise function
function promiseWhile(predicate, action) {
console.log('in while');
function loop() {
if (!predicate) return;
return Promise.resolve(action()).then(loop);
}
return Promise.resolve().then(loop);
}
categoryFacade.findAllMainCategories()
.then((mainCategories) => {
return Promise.all(mainCategories.map((mainCategory) => {
console.log(JSON.stringify(mainCategory.name, null, 0));
catStack.push(mainCategory);
return mainCategory;
}));
})
.then(promiseWhile(!catStack.empty(), function() {
console.log('in action');
let nextToProcess = catStack.pop();
layer += 2;
console.log(JSON.stringify(nextToProcess.name, null, layer));
return categoryFacade.findAllChildrenOf(nextToProcess.name)
.then(allChildren => Promise.all(allChildren.map((child) => {
catStack.push(child);
return child;
})));
}))
【问题讨论】:
-
const stack = new stack;没有意义——它会产生解析错误。还缺少右括号。另外,A和a??但是经过这些更正后,代码可能仍然很奇怪,但它会在弹出之前产生推送。请提供一个能重现您的问题的 sn-p。 -
语法错误太多
标签: javascript asynchronous promise