2017-03-08 21 views
0

私はいくつかのメソッドを試してみましたが、読んでいましたが、この関数から名前配列を返す方法を理解できないようです。この約束からどのように配列を返すことができますか?

function getNames(oauth2Client, docs) { 
const api = x('v1'); 

let names = []; 

return Promise.each(docs, function(doc) { 
     let req = api.users.messages.get; 

     let options = ({ 
      auth: oauth2Client, 
      'userId': 'me', 
      'id': doc.id 
     }); 

     return Promise.promisify(req)(options).then(function(response) { 
      for (y = 0; y < response.names.length; y++) {    
       names.push(response.names[y].toLowerCase());     
      } 
     }) 
     .catch(function (err) { 
      console.log('An error occured: ' + err.message); 
      throw err; 
     }); 
    }); 
} 

答えて

1

あなたが使用しているPromiseライブラリが標準ではないように見えますが、このようなものはあなたが望むものだと思います。私は何が起こっているのかについてのコメントを追加しました。あなたの約束のライブラリに合うようにこれらのコード行を変更する必要があります。

function getNames(oauth2Client, docs) { 
    const api = x('v1'); 
    const names = []; 
    // create a stack of promises 
    const stack = []; 
    docs.forEach(doc => { 
     let req = api.users.messages.get; 
     let options = ({ 
      auth: oauth2Client, 
      'userId': 'me', 
      'id': doc.id 
     }); 
     // push each promise onto the stack 
     stack.push(
      Promise.promisify(req)(options).then(function(response) { 
       for (y = 0; y < response.names.length; y++) {    
        names.push(response.names[y].toLowerCase());     
       } 
      }) 
      .catch(function (err) { 
       console.log('An error occured: ' + err.message); 
       throw err; 
      }) 
     ); 
    }); 
    // Wait for all promises in the stack to finish, and then 
    // return the names array as the final value. 
    return Promise.all(stack).then(() => names); 
} 
+0

は[ 'Promise'コンストラクタアンチパターン](http://stackoverflow.com/q/23803743を避けてください/ 1048572?約束の建設 - 反パターン - と - 回避する方法 - それは)です! – Bergi

+0

ありがとう@Bergi - 私は怠け者でした。コードが更新されました。 –

+1

ありがとうございます。 Btw、約束の図書館はBluebird – Bergi

1

単にnames配列を満たすために返された約束を引き起こし

return Promise.each(…) 
.then(function() { 
    return names; 
}); 

を追加します。

しかし、特に結果の順序が気になる場合は、eachループでグローバル配列を使用しないことをお勧めします。代わりに、値を持つすべての約束を解決map代わりのeachを使用して、最後に結果を組み合わせる:

const api = x('v1'); 
const getUserMessages = Promise.promisify(api.users.messages.get); 

function getNames(oauth2Client, docs) { 
    return Promise.map(docs, doc => 
     getUserMessages({ 
      auth: oauth2Client, 
      'userId': 'me', 
      'id': doc.id 
     }) 
     .then(response => 
      response.names.map(name => name.toLowerCase()); 
     ) 
    ) 
    .then(nameArrays => 
     [].concat(...nameArrays) 
    ); 
} 
関連する問題