如何处理异步函数和集合
How to deal with async functions and collections?
假设我们有一个函数foo(item, callback)
和一个集合items
。
我想做的是用执行foo
返回的值替换items
中的每个项,就像Array.map()
一样。
但问题来了:foo
的结果是在回调中产生的,所以我在回调之外无法访问它(显然我无法更改foo
来满足我的需求)。
你可以试试这样的方法
var results = [];
items.map((function(el) {
foo(el, function(result) {results.push(time)});
});
但是,您不知道results
系列何时"准备就绪"。
我完全没有头绪我该怎么办?模式是什么
EDIT:我更感兴趣的是Vanilla Javascript实现这一点的方法,而不是工具/库,它们无论如何都是可以接受的答案
在香草JS中,我会这样做:
var items = ['item 1', 'item 2', 'item 3']
function foo(item, callback) {
// this is provided just to test the async nature of your callback
setTimeout(function () {
callback.call(null, item + ' async')
}, Math.random() * 5000);
}
var results = [];
var count = 0;
items.forEach(function (element, index, array) {
foo(element, function (result) {
results[index] = result;
// the actual "ready" check
if (++count == items.length) {
// here you should notify your code that all items have been replaced
// after a random number of seconds between 1 and 5 in the current example, it should
// write ['item 1 async', 'item 2 async', 'item 3 async']
console.log(results);
}
})
});
我不知道这是一种模式还是最好的方法,但我认为它简单快捷。请注意,forEach仅适用于IE9+。对于IE<9可以使用jQuery.each,也可以手动编写for循环(但要小心闭包和索引)。
当使用异步库时,这变得非常琐碎。
async.each(items, function(el, callback) {
foo(el, function(result) {
callback(result);
});
}, function(results) {
doSomethingWith(results); //results being an array of the callbacked results.
});
相关文章:
- 如何在异步函数中使用javascript对象
- Meteor:异步函数回调异常:onAfterAction
- 未调用jquery异步函数
- 使用来自不同异步函数的响应创建一个json对象
- 如何在异步函数中正确使用Promise.all()和then()
- 从异步函数返回值
- 如何按照承诺使用mocha/chai/chai测试ES7异步函数
- 如何在将Node异步函数转换为promise时使用Q库
- 如何在异步函数与Deferredjquery之间同步
- ng用异步函数模拟怪异行为
- 用mocha测试异步函数
- 用于异步函数中的循环和定时问题
- Node.js设计:多个异步函数使用作为闭包传递的函数写入数据库
- 嵌套异步函数未及时返回数据的问题
- 在异步函数中维护变量的状态
- 递归异步函数
- Bluebird promisifyAll不会创建整个异步函数集
- 递归调用异步函数
- 异步函数调用是否可以在两个同步语句之间完成
- 如何在nodejs中实现异步函数