2017-11-27 4 views
0

約束を使ってforEachループの後に値を返す方法を知る必要があります。この瞬間に、私は私のメインを起動したとき、私が取得:約束事を使用してforEachループの後に値を返す方法はありますか?

[ Promise { <pending> }, Promise { <pending> } ] 

(私のsampleidlistのみ2レコードを含む) これは私のコードです:

MongoClient.connect("mongodb://127.0.0.1/myproject", function(err, db) { 
    return db.collection('RUN').find({ 
     "idRun": query.idRun 
    }).toArray() 
    .then((out) => { 

     var sampleidlist = out[0].SAMPLE_ID 
     var pazlist = [] 
     // Promisearr is the array of promises where I try to push the promises 
     var Promisearr = [] 
     // there is the function find_paz that return idPaz for every sampleId in sampleidlist       
     function find_paz(sampleid) { 
     // I return a new Promise for every sampleId 
     // I want to create an array of idPaz 
     return new Promise((resolve, reject) => { 
      db.collection('PATIENTS').find({ 
       "SAMPLE_ID": sampleid 
      }).toArray() 
      .then((pazArr) => { 
       var singlepaz = [] 
       singlepaz.push(pazArr[0].idPaz) 
       return singlepaz 
      }) 
      .then((singlepaz) => { 
       pazlist.push(singlepaz) 

      }) 
     }) 
     } 
     // Here the forEach loop 
     sampleidlist.forEach(sampleid => { 
     Promisearr.push(
      find_paz(sampleid) 
     ) 
     }) 
     Promise.resolve(Promisearr) 
     .then(Promise.all(Promisearr)) 
     .then(value => { 
      // value return {promise<pending>} 
      // I want that value is the array of idPaz 
      console.log(value) 
     }).catch((err) => { 
      console.log('errored', err); 
     }) 

    }).catch((err) => { 
     console.log('errored', err); 
    }) 
}) 

任意の提案しますか? ありがとうございました:)

+0

[非同期呼び出しからの応答を返すにはどうすればよいですか?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous -call) – Liam

+1

'find_paz'で各約束を解決するか拒否する必要があり、約束事の配列で' Pomise.all() 'だけを使う必要があります – charlietfl

答えて

0

あなたはPromise.allとPromise.resolveの間で混ざっています。ここで:

戻りdb.collection( 'RUN')({ "idRun":query.idRun })を見つける。。のtoArray() .then((OUT)=> {

var sampleidlist = out[0].SAMPLE_ID 
    var pazlist = [] 

    var Promisearr = [] 

    function find_paz(sampleid) { 

     return db.collection('PATIENTS').find({ 
      "SAMPLE_ID": sampleid 
     }).toArray() 
     .then((pazArr) => { 
      var singlepaz = [] 
      singlepaz.push(pazArr[0].idPaz) 
      return singlepaz 
     }) 
     .then((singlepaz) => { 
      pazlist.push(singlepaz) 
      return; 
     }) 
    }) 
    } 
    Promise.all(sampleidlist.map(find_paz)) 
    .then(values => { 

     //values is an array with all the promises resolved 
     //pazlist should have your data. 
    }).catch((err) => { 
     console.log('errored', err); 
    }) 

}).catch((err) => { 
    console.log('errored', err); 
}) 

それが動作しない場合、私はあなたが明確化が必要な場合は知っているか聞かせて、それを試してみる

0

をあなたがPromise.resolve()Promise.all()間違った方法を使用しているあなたはちょうどこのように、その後、.then()Promise.all()を呼び出す必要があります。。

Promise.all(Promisearr).then(value => 
    console.log(value) 
) 
関連する問題