【问题标题】:How to pass array in URLs as parameter in Promise.all如何将 URL 中的数组作为参数传递给 Promise.all
【发布时间】:2020-04-29 17:42:29
【问题描述】:

如何在 Promise.all 中将 url_user 数组作为参数传递?

我使用 Node.js 和 Express。

url_project = 'https://api.projects'
url_user = [
   'https://api.users/1',
   'https://api.users/2',
   'https://api.users/3',
   'https://api.users/4',
   'https://api.users/5',
   'https://api.users/6'
]

index.js

<div>
   <%= projectsApi.id %>
   <% for (var i = 0; i < usersApi.length; i++) { %>
        <%= usersApi[i].id %>
   <% } %>
</div>

server.js

var rp = require('request-promise');

Promise
     .all([rp({uri: url_project, json:true}), rp({uri: url_user, json:true})]) //This where I want to edit
     .then(([projectsApi, usersApi]) => {
         res.render('index', {projectsApi, usersApi});
     }).catch(err => {
         console.log(err);
         res.sendStatus(500);
     });

当我输入Promise.all([rp({uri: url_project, json:true}), rp({uri: url_user[0], json:true})]) 时,它可以工作,因为url_user[0] 不是一个数组。

但是我想传递数组url_user中的所有数据。

【问题讨论】:

    标签: node.js rest api express promise


    【解决方案1】:

    您可以使用mapspread operator

    url_project = 'https://api.projects'
    
    url_user = [
       'https://api.users/1',
       'https://api.users/2',
       'https://api.users/3',
       'https://api.users/4',
       'https://api.users/5',
       'https://api.users/6'
    ]
    
    const promises = [
      rp({uri: url_project, json:true}),
      ...url_user.map(value => rp({uri: value, json:true})
    ];
    
    Promise.all(promises)
      .then(values => {
        console.log(values);
        // Adjust your response
        // ...
      })
      .catch(err => {
        console.log(err);
        res.sendStatus(500);
      });
    

    【讨论】:

    • 谢谢。当我打印出console.log(usersApi) 时,它显示了不同的 JSON 数据,即 url 信息,但 url_user 数据。
    【解决方案2】:

    这应该可行:

    const url_project = 'https://api.projects'
    
    const url_user = [
       'https://api.users/1',
       'https://api.users/2',
       'https://api.users/3',
       'https://api.users/4',
       'https://api.users/5',
       'https://api.users/6'
    ]
    
    const promises = [
      rp({uri: url_project, json:true}),
      ...url_user.map(value => rp({uri: value, json:true})
    ];
    
    Promise
         .all(promises)
         .then(([projectsApi, ...usersApi]) => {
             res.render('index', {projectsApi, usersApi});
         }).catch(err => {
             console.log(err);
             res.sendStatus(500);
         });
    

    如果有任何问题,请告诉我。

    【讨论】:

    • 当我打印出console.log(usersApi)时,它显示了不同的JSON数据,即url信息,而不是url_user数据。
    • 你能告诉我console.log(usersApi)的输出,或者至少是响应的结构吗?
    • url : { [...] }, method : "GET", headers : { accept : "application/json" } ...
    • 对于其他上下文,console.log(projectsApi) 的输出是什么?
    • 嗯,奇怪,它应该可以工作。你能告诉我你的实际代码吗?
    【解决方案3】:

    代码块:

    const rp = require('request-promise');
    const _ = require('lodash'); //lodash is awesome, otherwise u can use JS map/concat
    
    const projectUrl = 'https://api.projects';
    
    const userUrls = [
      'https://api.users/1',
      ...,
      ...,
    ];
    
    const promises =  
      _(projectUrl)
        .concat(userUrls)
        .map((requestUrl) -> rp({uri: requestUrl, json:true}))
        .value()
    
    await Promise
      .all(promises)      
      .then((results) => {
        res.render('index', {projectsApi: results.shift(), usersApi: ...results});
      }).catch(err => {
        console.log(err);
        res.sendStatus(500);
      });
    

    解释:

    Steps:
     - Get all requests together
     - Map over each using lodash or js map to get promises
     - Execute them together
     - Since project_url is the first request the result is the first item in array
     - Spread the reset of the result to get user results
    

    【讨论】:

    • 谢谢。我怎样才能完成这部分代码? res.render('index', {projectsApi: results.shift(), usersApi: ...results});
    • 响应结构是什么?可能,JSON.stringify 结果并粘贴结果
    • 网址:{ [...] },方法:“GET”,标头:{ 接受:“application/json”} ...
    猜你喜欢
    • 2012-10-17
    • 2017-03-22
    • 1970-01-01
    • 2014-07-24
    • 2015-02-19
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    相关资源
    最近更新 更多