Mar*_*ser 5 javascript node.js
几分钟前我问过循环,请参阅JavaScript中的Asynchronous for cycle.
这一次,我的问题是 - Node.js有什么模块吗?
for ( /* ... */ ) {
// Wait! I need to finish this async function
someFunction(param1, praram2, function(result) {
// Okay, continue
})
}
alert("For cycle ended");
Run Code Online (Sandbox Code Playgroud)
将这些东西移到模块中很难吗?
编辑:更新了代码。
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;
Run Code Online (Sandbox Code Playgroud)
还有一个小测试:
// 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')}
);
Run Code Online (Sandbox Code Playgroud)
剩下的就看你自己了,不可能100%通用。
| 归档时间: |
|
| 查看次数: |
3352 次 |
| 最近记录: |