2016-10-18 2 views
0

테이블에서 일부 태그 이름을 얻은 다음 각자 다른 하나를 검색 할 필요가 있지만 또는 이와 유사한 방식으로 을 수행 할 수 없습니다. 이 문제를 해결할 다른 방법이 있습니까?복수 쿼리 sequelize

db.archivos.findAll({ 
    attributes: ['nombre','texto','related'], 
     where: { 
      nombre: nombre 
     }, 
     raw: true 
     }).then(function(archivos){ 
      if(archivos.length != 0){ 
       tags = archivos[0].related.split('/'); 
       cantTags = tags.length; 


       for(i=0; i < cantTags; i++){ 
       db.tags.findAll({ 
       attributes: ['paginasRelacionadas'], 
        where: { 
         nombre: tags[i] 
        }, 
        raw: true 
       }).then(function(query){ 
        related += paginasRelacionadas 
       }); 
       } 
      } 

답변

0

당신은 비동기 문제를 해결하기 위해 Promises와 함께 일할 수 있습니다. 당신이 게시 한 코드를 보면,이 같은 트릭 (사용 ES2015)를해야한다고 생각 :

db.archivos.findAll({ 
    attributes: ['nombre','texto','related'], 
    where: { 
     nombre: nombre 
    }, 
    raw: true 
}).then((archivos) => 
{ 
    const findTags => (related, tags, i=0) 
    {   
     const tag = tags[i]; 

     if(!tag) 
      return Promise.resolve(related); 

     return db.tags.findAll({ 
      attributes: ['paginasRelacionadas'], 
      where: { 
       nombre: tag 
      }, 
      raw: true 
     }).then(function(newRelated){ 
      related.push(...newRelated); 
      return findTags(related, tags, ++i); 
     });  
    }; 

    if(!archivos.length) 
     return archivos; 

    const tags = archivos[0].related.split('/'); 
    return findTags(archivos.related, tags).then((related) => 
    { 
     archivos[0].related = related; 
     return archivos; 
    }); 

}).then((archivos) => 
{ 
    //do whatever you want with the archivos (here the 
    //first item will have the related properties with 
    //the new values) 
}) 
0

@demarchisd가 올바른지. 결과를 반복적으로 반복하는 대신 약속을 반복해야합니다. 다음과 같음 :

return db.Pormise.all(tags.map(function(tag)=>{ 
    db.tags.findAll({ 
    attributes: ['paginasRelacionadas'], 
     where: { 
      nombre: tags[i] 
     }, 
     raw: true 
    }).then(function(query) { 
     related += query.paginasRelacionadas; 
    }); 
}));