Seb*_*ebi 0 javascript asynchronous node.js
我是node.js的新手,我想知道是否可以同步循环迭代.让我们说在for循环中我调用一个阻塞函数(读取,写入),我希望for执行同步(等待第一次迭代完成,然后执行第二次迭代,......)?我看到了一些关于异步模块的教程,但没有人介绍过这个问题.
你不应该为此使用for循环.该for循环将同时激发关闭每个异步功能,这显然不是你想要的.您应该创建自己的系统来调用它们.尝试这样的事情:
应该看起来像这样:
var urls = new Array("google.com", "youtube.com", "stackoverflow.com");
function callFirstInArray() {
var url = urls.shift(); //removes the first from the array, and stores in variable 'url'
//do ajax work, and set callback function:
$.ajax(/*do stuff with the url variable*/, function () {
if (urls.length > 0) { //callback
callFirstInArray();
};
});
};
Run Code Online (Sandbox Code Playgroud)
您可能无法完全按照我在此描述的方式工作,但它应该使用类似的概念.
注意:您可能需要一个额外的函数范围来保护原始的URL数组,因为它.shift()会改变原始数组
| 归档时间: |
|
| 查看次数: |
6655 次 |
| 最近记录: |