gpt4 book ai didi

javascript - 涵盖 for 循环和异步回调的通用解决方案

转载 作者:行者123 更新时间:2023-11-30 09:56:35 28 4
gpt4 key购买 nike

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

如果处理是同步的,下面是可以工作的代码

    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 次深度递归。

最佳答案

如果您有可能使用转译器,我建议您查看 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]);

看看下面运行的转译代码:

'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]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.33/browser-polyfill.min.js"></script>

<ul>

</ul>

关于javascript - 涵盖 for 循环和异步回调的通用解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33645088/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com