Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 嵌套解析承诺外的空数组_Javascript_Node.js_Foreach_Promise_Lodash - Fatal编程技术网

Javascript 嵌套解析承诺外的空数组

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) 。然后(项目=>{ 如

im尝试将解析的返回值推送到解析之外的变量
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()
,是的,我没有正确处理承诺。你的例子很有用。非常感谢。