【问题标题】:Converting async/await function to ES5 equivalent将 async/await 函数转换为 ES5 等效函数
【发布时间】:2020-02-28 23:13:48
【问题描述】:

我正在重写一个批量执行 REST API 调用的应用程序,例如一次执行 10 次总共 500 次调用。我需要帮助将使用 ES6+ 函数的 js 函数降级为 ES5 等效函数(基本上没有箭头函数或异步/等待)。

在支持 ES6+ 函数(箭头函数、异步/等待等)的环境中使用的原始应用程序中,我的工作函数如下:

原功能:

// Async function to process rest calls in batches
const searchIssues = async (restCalls, batchSize, loadingText) => {
    const restCallsLength = restCalls.length;
    var issues = [];
    for (let i = 0; i < restCallsLength; i += batchSize) {
        //create batch of requests
        var requests = restCalls.slice(i, i + batchSize).map((restCall) => {
            return fetch(restCall)
                .then(function(fieldResponse) {
                    return fieldResponse.json()
                })
                .then(d => {
                    response = d.issues;

                    //for each issue in respose, push to issues array
                    response.forEach(issue => {
                        issue.fields.key = issue.key
                        issues.push(issue.fields)
                    });
                })
        })
        // await will force current batch to resolve, then start the next iteration.
        await Promise.all(requests)
            .catch(e => console.log(`Error in processing batch ${i} - ${e}`)) // Catch the error.

        //update loading text
        d3.selectAll(".loading-text")
            .text(loadingText + ": " + parseInt((i / restCallsLength) * 100) + "%")

    }

    //loading is done, set to 100%
    d3.selectAll(".loading-text")
        .text(loadingText + ": 100%")
    return issues
}

例如,到目前为止,我编写的代码正确地批处理了第一组 10 个中的其余调用,但我似乎在解决 Promise 时遇到了问题,因此 for 循环可以继续迭代。

我正在重写的函数:

//Async function process rest calls in batches
    function searchIssues(restCalls, batchSize, loadingText) {
        const restCallsLength = restCalls.length;
        var issues = [];
        for (var i = 0; i < restCallsLength; i += batchSize) {
            //create batch of requests
            var requests = restCalls.slice(i, i + batchSize).map(function(restCall) {
                    return fetch(restCall)
                        .then(function(fieldResponse) {
                            return fieldResponse.json()
                        })
                        .then(function(data) {
                            console.log(data)
                            response = data.issues;

                            //for each issue in respose, push to issues array
                            response.forEach(function(issue) {
                                issue.fields.key = issue.key
                                issues.push(issue.fields)
                            });
                        })
                })
                //await will force current batch to resolve, then start the next iteration.
            return Promise.resolve().then(function() {
                console.log(i)
                return Promise.all(requests);
            }).then(function() {
                d3.selectAll(".loading-text")
                    .text(loadingText + ": " + parseInt((i / restCallsLength) * 100) + "%")
            });
            //.catch(e => console.log(`Error in processing batch ${i} - ${e}`)) // Catch the error.
        }

         //loading is done, set to 100%
         d3.selectAll(".loading-text")
             .text(loadingText + ": 100%")
         return issues
    }

我的问题是,一旦我的 10 个 restCalls 完成,我该如何正确解决 Promise 并继续遍历 for 循环

作为参考,我尝试使用 Babel 编译原始函数,但它无法在我的 Maven 应用程序中编译,因此从头开始重写。

【问题讨论】:

  • “我尝试使用 Babel 编译原始函数,但它无法在我的 Maven 应用程序中编译”是什么意思?真可惜,您不应该从头开始重写所有内容
  • @blex 我正在编写的应用程序是一个 Jira 插件,它的服务器版本是使用我相对不熟悉的 java 后端 (Maven) 启动的。错误消息非常简单,因此很难确定该函数的 Babel 转录版本为什么不起作用。

标签: javascript maven


【解决方案1】:

没有async/await,您无法暂停for 循环。但是您可以通过使用递归函数来重现该行为,在每批 10 个之后调用自身。类似这些行的东西(未测试)

// Async function to process rest calls in batches
function searchIssues(restCalls, batchSize, loadingText) {
  var restCallsLength = restCalls.length,
      issues = [],
      i = 0;

  return new Promise(function(resolve, reject) {
    (function loop() {
      if (i < restCallsLength) {
        var requests = restCalls
          .slice(i, i + batchSize)
          .map(function(restCall) {
            return fetch(restCall)
              .then(function(fieldResponse) {
                return fieldResponse.json();
              })
              .then(function(d) {
                var response = d.issues;

                //for each issue in respose, push to issues array
                response.forEach(issue => {
                  issue.fields.key = issue.key;
                  issues.push(issue.fields);
                });
              });
          });

        return Promise.all(requests)
          .catch(function(e) {
            console.log(`Error in processing batch ${i} - ${e}`);
          })
          .then(function() {
            // No matter if it failed or not, go to next iteration
            d3.selectAll(".loading-text").text(
              loadingText + ": " + parseInt((i / restCallsLength) * 100) + "%"
            );
            i += batchSize;
            loop();
          });
      } else {
        // loading is done, set to 100%
        d3.selectAll(".loading-text").text(loadingText + ": 100%");
        resolve(issues); // Resolve the outer promise
      }
    })();
  });
}

【讨论】:

    猜你喜欢
    • 2020-03-14
    • 1970-01-01
    • 2021-10-19
    • 2018-11-12
    • 2019-07-06
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多