2017-03-08 43 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

我不知道你用的是什么承诺库,因为它似乎不规范,但这样的事情,我认为是你想要的。我为正在发生的事情添加了评论 - 您可能需要更改这些代码行以适合您的承诺库。

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

谢谢。顺便说一句,诺言库是蓝鸟 – Bergi

1

只需添加

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

导致返回的承诺与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) 
    ); 
}