Javascript 嵌套解析承诺外的空数组
im尝试将解析的返回值推送到解析之外的变量Javascript 嵌套解析承诺外的空数组,javascript,node.js,foreach,promise,lodash,Javascript,Node.js,Foreach,Promise,Lodash,im尝试将解析的返回值推送到解析之外的变量catWithItems。在resolve内,catWithItems按预期工作,但当我在循环外记录catWithItems时,它返回一个空数组 功能分类搜索(req、res、next){ let categories=req.batch\u categories; 设catWithItems=[]; _.forEach(类别,(类别)=>{ 返回新承诺(解决=>{ pos.categoriesSearch(请求租户,类别id) 。然后(项目=>{ 如
catWithItems
。在resolve内,catWithItems按预期工作,但当我在循环外记录catWithItems时,它返回一个空数组
功能分类搜索(req、res、next){
let categories=req.batch\u categories;
设catWithItems=[];
_.forEach(类别,(类别)=>{
返回新承诺(解决=>{
pos.categoriesSearch(请求租户,类别id)
。然后(项目=>{
如果(项)category.items=项[0];
退货类别;
})
。然后(类别=>{
catWithItems.push(类别);
console.log(catWithItems);//这是在这里工作的
返回解析(catWithItems);
});
});
});
console.log(catWithItems);//不工作返回空数组
res.json({categorywhitems:catWithItems});
}
您处理承诺的方式不对。这样试试看
功能分类搜索(req、res、next){
let categories=req.batch\u categories;
让promiseArray=[];//创建一个数组来实现您的承诺
设catWithItems=[];
categories.map((categority)=>{
让承诺=新承诺(解决=>{
pos.categoriesSearch(请求租户,类别id)
。然后(项目=>{
如果(项)category.items=项[0];
退货类别;
})
。然后(类别=>{
catWithItems.push(类别);
console.log(catWithItems);//这是在这里工作的
返回解析(catWithItems);
});
});
promiseArray.push(promise)//向数组添加承诺
});
//并行解决所有承诺
Promise.all(promiseArray)。然后((已解决)=>{
console.log(已解决);
res.json({categorywhitems:catWithItems});
})
}
这应该容易得多。不确定它是否有效,但首先要做的是:
function categoriesSearch(req, res) {
const categoryWithItems$ = req.batch_categories.map(category =>
pos.categoriesSearch(req.tenant, category.id)
.then(item => ({ ...category, items: item[0] })
);
Promise.all(categoryWithItems$)
.then(categoryWithItems => res.json({ categoryWithItems });
}
可能只是一个猜测的重复,有一个方法说
foo()
它监听分类搜索(…)。然后((数据)=>res.json({categorywhitems:data});)
。所以在categoriesSearch()中不需要res.json()
,是的,我没有正确处理承诺。你的例子很有用。非常感谢。