如何将for循环查询Wix数据库的结果整合为单个可操作数组?
解决Wix Data查询结果整合为数组的问题
你的问题核心是异步操作的时序问题:wixData.query().find()是异步任务,原for循环会快速跑完所有迭代,但每个查询的then回调会在各自异步任务完成后才执行,导致每次只能拿到单个结果,无法正确整合。
修改方案
用Promise.all统一管理所有异步查询,等全部完成后再一次性收集结果:
// 把每个选中项的查询转换成Promise对象,存入数组 const queryTasks = selectedindex.map(item => wixData.query('MachinePricing') .contains('title', item) .find() ); // 等待所有查询任务完成 Promise.all(queryTasks) .then(allQueryResults => { const combinedPrices = []; allQueryResults.forEach(result => { if (result.items.length > 0) { // 提取当前查询结果里的所有prices,合并到总数组 const itemPrices = result.items.map(({ prices }) => prices); combinedPrices.push(...itemPrices); } }); console.log(combinedPrices); // 这里就是整合后的完整价格数组 }) .catch(err => { console.error('数据库查询失败:', err); });
关键说明
- 用
map替代for循环:把每个selectedindex元素对应的查询任务转换成Promise,批量存入数组 Promise.all:确保所有异步查询都完成后,才开始处理结果,避免时序混乱- 展开运算符
...:把每个查询返回的prices数组元素逐个添加到总数组里,避免出现嵌套数组
如果每个title只会对应一条数据,也可以简化提取逻辑:
// 只取每条查询结果的第一个item的prices const itemPrice = result.items[0].prices; combinedPrices.push(itemPrice);
内容的提问来源于stack exchange,提问作者Abdallah Mushi Nourdin
相关产品推荐
相关产品推荐

