覆盖循环和异步回调的通用解决方案

时间:2015-11-11 06:04:15

标签: javascript asynchronous

我的代码中有几个适合这种模式的场景,我确信它是一个常见的编程问题。我想循环遍历数组或对象,并在每次迭代时运行(可能)异步函数。我不希望下一次迭代开始,直到当前的迭代完成。

这里是处理是同步的代码

    var k;
    for (k in data) {
        var thisdata = data[k];
        dosomething(thisdata);
    }

在上面,dosomething可能会访问服务器,或者它可能会抛出一个用户输入的对话框,或者它可能只是在js中进行一些本地处理。

以下是我提出的解决方案:

    var keys = Object.keys(data);
    var index = 0;
    exec();

    function exec() {
        if (index == keys.length) return;
        var k = keys[index++];
        var thisdata = data[k];
        dosomething(thisdata, exec);
    }

因此必须修改dosomething()以进行回调,这很好,但是使用Object.keys并且具有这样不优雅且难以阅读的代码似乎是错误的。那么有更简单/更好的方法吗?

此循环也可能有数千次迭代,因此" stackoverflow"我想是一个问题,即。正在进行1000次深度递归。

3 个答案:

答案 0 :(得分:2)

如果您有可能使用转发器,我建议您查看ES7 async/await提案。您可以像这样编码,然后通过Babel(或Facebook Regenerator)进行转发:

const doSomething = (param) => {
  return new Promise((resolve, reject) => {
    // in my example, I'll do an AJAX request
    const xhr = new XMLHttpRequest();
    xhr.addEventListener('load', (res) => {
      if (xhr.status >= 200 && xhr.status < 300)
        resolve(JSON.parse(xhr.responseText));
      else
        reject(xhr.statusText);
    });
    xhr.addEventListener('error', (err) => {
      reject(err);
    });
    xhr.open('GET', 'https://api.github.com/repos/buzinas/tslint-eslint-rules/issues/' + param);
    xhr.send();
  });
}

const getData = async (data) => { 
  for (let d of data) {
    let result = await doSomething(d);
    document.querySelector('ul').insertAdjacentHTML('beforeend', `<li>${d}: ${result.title} - ${result.state}</li>`);
  }
};

getData([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

看看下面运行的已编译代码:

&#13;
&#13;
'use strict';

var _this = this;

var doSomething = function doSomething(param) {
  return new Promise(function (resolve, reject) {
    // in my example, I'll do an AJAX request
    var xhr = new XMLHttpRequest();
    xhr.addEventListener('load', function (res) {
      if (xhr.status >= 200 && xhr.status < 300) resolve(JSON.parse(xhr.responseText));else reject(xhr.statusText);
    });
    xhr.addEventListener('error', function (err) {
      reject(err);
    });
    xhr.open('GET', 'https://api.github.com/repos/buzinas/tslint-eslint-rules/issues/' + param);
    xhr.send();
  });
};

var getData = function getData(data) {
  var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, d, result;

  return regeneratorRuntime.async(function getData$(context$1$0) {
    while (1) switch (context$1$0.prev = context$1$0.next) {
      case 0:
        _iteratorNormalCompletion = true;
        _didIteratorError = false;
        _iteratorError = undefined;
        context$1$0.prev = 3;
        _iterator = data[Symbol.iterator]();

      case 5:
        if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
          context$1$0.next = 14;
          break;
        }

        d = _step.value;
        context$1$0.next = 9;
        return regeneratorRuntime.awrap(doSomething(d));

      case 9:
        result = context$1$0.sent;

        document.querySelector('ul').insertAdjacentHTML('beforeend', '<li>' + d + ': ' + result.title + ' - ' + result.state + '</li>');

      case 11:
        _iteratorNormalCompletion = true;
        context$1$0.next = 5;
        break;

      case 14:
        context$1$0.next = 20;
        break;

      case 16:
        context$1$0.prev = 16;
        context$1$0.t0 = context$1$0['catch'](3);
        _didIteratorError = true;
        _iteratorError = context$1$0.t0;

      case 20:
        context$1$0.prev = 20;
        context$1$0.prev = 21;

        if (!_iteratorNormalCompletion && _iterator['return']) {
          _iterator['return']();
        }

      case 23:
        context$1$0.prev = 23;

        if (!_didIteratorError) {
          context$1$0.next = 26;
          break;
        }

        throw _iteratorError;

      case 26:
        return context$1$0.finish(23);

      case 27:
        return context$1$0.finish(20);

      case 28:
      case 'end':
        return context$1$0.stop();
    }
  }, null, _this, [[3, 16, 20, 28], [21,, 23, 27]]);
};

getData([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.33/browser-polyfill.min.js"></script>

<ul>

</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

以下是使用async的示例。代码在数据中的任何偶数上运行异步函数。

var async = require('async');

var data = [10, 11, 22, 33, 14, 11, 6, 57, 8, 49];

// Waits 2 seconds then prints the data (async)
// Notice the added parameter for the callback
function doSomething(data, done) {
    setTimeout(function() {
        console.log('async', data);
        done();
    }, 2000);
}

// Go through each member of the data
async.each(data, function(thisdata, callback) {

    // Make async call if the number is even
    // Replace this with whatever logic you have for potentially running the async function
    if (thisdata % 2 === 0) {

        // Pass the data and the callback!
        doSomething(thisdata, callback);
    } 

    // Else make the callback right away
    else {
        callback();
    }
}, 
function() {
    console.log('all done');
});

答案 2 :(得分:1)

这是一个没有外部库的通用函数(Promise Internet Exploder除外) - 当然,可以使用诸如https://www.promisejs.org/polyfills/promise-7.0.4.js

之类的polyfill将Promises添加到internet exploder中
function inSeries(array, fn) {
    var promises = [];
    array.reduce(function(ret, v) { 
        var promise = ret.then(fn.bind(null, v)).then(
            function(x) { return {state: "fulfilled", value: x};}, 
            function(e) { return {state: "rejected" , value: e};}
        );
        promises.push(promise);
        return promise;
    }, Promise.resolve());
    return Promise.all(promises);
}

传递一个值数组,以及一个接受单个参数的函数(即每个参数中的值)

该函数可以返回Promise或值,无论

返回的promise是函数每次迭代的结果数组,格式为

{state: 'fulfilled or rejected', value: 'result or error'}

如果您在问题中有“源”数据不是数组,则可以调用函数

inSeries(Object.keys(theData).map(function(key) {
    return theData[key];
}), someFunction).then( //etc

这是一个演示 - http://jsfiddle.net/p5ojdhLc/