미리 감사드립니다. 누군가 내 요청의 각 속성에 대해 다른 쿼리를 어떻게 실행할 수 있는지 설명해 주시겠습니까? 사용자가 확인란 값을 변경할 때 검색 사이드 바 메뉴를 만들려고합니다. 이러한 속성을 사용하여 개체를 만듭니다.
{
"category": [
"electronics",
"clothing",
"pets"
],
"condition": [
"old",
"new"
]
}
쿼리를 함수 배열로 푸시 한 다음 async.parallel을 사용하여 실행하고 싶습니다. 호출 될 때 모든 쿼리의 결과를 포함하는 하나의 배열 안에 각 쿼리의 결과를 푸시하고 싶습니다.
router.get('', async function(req,res)
{
var searchResults = [];
if(req.query.filters)
{
const queryObj = JSON.parse(req.query.filters);
var searchQueries = [];
if(queryObj.category){
searchQueries.push(async function (cb) {
return await Rentals.find({/* SOME CONDITION */}).populate('-something').exec(function (err, docs) {
if (err) {
throw cb(err);
}
cb(null, docs);
});
})
}
if(queryObj.condition){
searchQueries.push(async function (cb) {
return await Rentals.find({/* SOME CONDITION */}).populate('-something').exec(function (err, docs) {
if (err) {
throw cb(err);
}
cb(null, docs);
});
})
}
async.parallel(searchQueries, function(err, foundRentals) {
if (err) {
throw err;
}
searchResults.push(foundRentals[0]); // result of searchQueries[0]
searchResults.push(foundRentals[1]); // result of searchQueries[1]
searchResults.push(foundRentals[2]); // result of searchQueries[2]
})
}
res.json(searchResults);
});
문제는 searchResults를 반환 할 때 발생하며 서버에서 빈 배열을 수신하지만 응답이 전송 된 후 쿼리가 완료되고 응답이 전송 된 후 결과를 얻습니다. 모든 쿼리를 동시에 실행하고 모든 쿼리가 완료 될 때까지 기다렸다가 클라이언트에 응답을 보내려면 어떻게해야합니까?
귀하의 promise.all
코드 버전이 다음과 같이합니다 :
router.get('', async function(req,res)
{
try{
let searchResults = [],
categoryPromises = [],
conditionPromises = [];
if(req.query.filters)
{
const queryObj = JSON.parse(req.query.filters);
if(queryObj.category && queryObj.category.length > 0){
categoryPromises = queryObj.category.map(singleCategory=>{
return Rentals
.find({/* SOME CATEGORY? */})
.populate('-something')
.exec();
});
}
if(queryObj.condition && queryObj.condition.length > 0){
conditionPromises = queryObj.category.map(singleCondition=>{
return Rentals
.find({/* SOME CONDITION */})
.populate('-something')
.exec();
});
}
searchResults.push(await categoryPromises);
searchResults.push(await conditionPromises);
}
res.json(searchResults);
}catch(e){
// catch-all error handling here
}
});
(.map 대신 for 루프를 사용하여 categoryPromises 배열로 푸시 할 수도 있습니다)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다