【问题标题】:Do all axios calls before returning JSON在返回 JSON 之前执行所有 axios 调用
【发布时间】:2017-12-15 19:51:40
【问题描述】:

我正在创建一个 API 服务器,在其中,我需要调用在另一个 API 服务器上找到的转换方法来获取负值。我相信我的代码是正确的,但是由于 ASYNC,我相信它会在进行所有转换之前返回值。代码如下:

                     for(let i = 0; i < results.length; i++) { 
                        if (parseInt(results[i]['ACCOUNT_ID']) < 0) {
                          let account = axios.get('http://localhost:54545/api?request=convert&id='+results[i]['ACCOUNT_ID'])
                            .then(function (response) {
                              results[i]['ACCOUNT_ID'] = response.data.stringId;console.log(response.data.stringId);
                            })
                            .catch(function (error) {
                              console.log(error);
                            });
                        }
                      }

                      res.setHeader('Content-Type', 'application/json');
                      return res.status(200).json(results);

我想我需要以某种方式使用 Promise.all,但我不确定如何使用它。
任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: javascript node.js promise axios


    【解决方案1】:

    你可以这样做

    let arrayOfPromises = [];
    for(let i = 0; i < results.length; i++) { 
        if (parseInt(results[i]['ACCOUNT_ID']) < 0) {
            arrayOfPromises.push(axios.get('http://localhost:54545/api?request=convert&id='+results[i]['ACCOUNT_ID']));
         }
        }
        Promise.all(arrayOfPromises).then( (responses) =>  {
                ///do stuff here
            })
            .then( () => {
                res.setHeader('Content-Type', 'application/json');
            })
            .catch(function (error) {
                console.log(error);
            });
        
        
        return res.status(200).json(results);
    So you are going to be pushing all of the axios async calls into an
    array
    
    Then Promise.all all of those async calls
    
    .then of of that
    
    You will then have an array of all of the axios calls, so you can do
    whatever logic you are trying to do
    
    then set the headers 
    
    finally return
    

    您也可以使用 Bluebird .spread 运算符 http://bluebirdjs.com/docs/api/spread.html 如果你知道进来的顺序。

    你也可以在 ES6 中使用扩展运算符https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      您可以使用axios.all 方法来解决所有的承诺。这是来自 axios 文档的示例,这里是链接https://github.com/mzabriskie/axios

      function getUserAccount() {
        return axios.get('/user/12345');
      }
      
      function getUserPermissions() {
        return axios.get('/user/12345/permissions');
      }
      
      axios.all([getUserAccount(), getUserPermissions()])
        .then(axios.spread(function (acct, perms) {
          // Both requests are now complete
      }));
      

      【讨论】:

        猜你喜欢
        • 2021-08-02
        • 2017-05-24
        • 1970-01-01
        • 2019-06-11
        • 1970-01-01
        • 2019-12-16
        • 2013-03-13
        • 1970-01-01
        • 2019-08-01
        相关资源
        最近更新 更多