admin管理员组文章数量:1420086
Few minutes ago I asked about looping, see Asynchronous for cycle in JavaScript.
This time, my question is - Is there any module for Node.js?
for ( /* ... */ ) {
// Wait! I need to finish this async function
someFunction(param1, praram2, function(result) {
// Okay, continue
})
}
alert("For cycle ended");
Few minutes ago I asked about looping, see Asynchronous for cycle in JavaScript.
This time, my question is - Is there any module for Node.js?
for ( /* ... */ ) {
// Wait! I need to finish this async function
someFunction(param1, praram2, function(result) {
// Okay, continue
})
}
alert("For cycle ended");
Share
Improve this question
edited May 23, 2017 at 12:00
CommunityBot
11 silver badge
asked Nov 26, 2010 at 23:02
Marry HoffserMarry Hoffser
9551 gold badge8 silver badges5 bronze badges
1
- So you effectively want to call the method synchronously? – thejh Commented Nov 26, 2010 at 23:05
2 Answers
Reset to default 3Is is that hard to move the stuff over into a module?
EDIT: Updated the code.
function asyncLoop(iterations, func, callback) {
var index = 0;
var done = false;
var loop = {
next: function() {
if (done) {
return;
}
if (index < iterations) {
index++;
func(loop);
} else {
done = true;
callback();
}
},
iteration: function() {
return index - 1;
},
break: function() {
done = true;
callback();
}
};
loop.next();
return loop;
}
exports.asyncFor = asyncLoop;
And a small test:
// test.js
var asyncFor = require('./aloop').asyncFor; // './' import the module relative
asyncFor(10, function(loop) {
console.log(loop.iteration());
if (loop.iteration() === 5) {
return loop.break();
}
loop.next();
},
function(){console.log('done')}
);
Rest is up to you, it's impossible to make this 100% generic.
Yes, you can use Async.js.
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with node.js, it can also be used directly in the browser.
本文标签: javascriptLoop module for NodejsStack Overflow
版权声明:本文标题:javascript - Loop module for Node.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745308935a2652817.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论