节点JS用于NOT异步
Node JS for NOT asynchronous
我已经构建了我的第一个Node应用程序。它会收到一份报价清单,然后我必须收到报价中每件商品的价格。
现在的问题是,我正在使用for
来遍历offers对象,比如
for(var k = 0; k < offers_object.length; k++){
offer = offers_object[k];
logger.info('Time Loaded is '+Math.floor(new Date() / 1000));
....
some stuff...
....
logger.info('Time request is '+Math.floor(new Date() / 1000));
....
send request
....
some more stuff after the requst
}
现在的问题是,在for循环中需要做的任何事情似乎都不是同步运行的。我使用API请求商品价格,这限制了我每秒8次请求。
我从计时器上得到的是:
info: Time Loaded is 1448409307
info: Time Loaded is 1448409307
info: Time Loaded is 1448409307
info: Time Loaded is 1448409307
info: Time Loaded is 1448409307
info: Time Loaded is 1448409307
info: Time Loaded is 1448409307
info: Time request is 1448409308
info: Time request is 1448409308
info: Time request is 1448409308
info: Time request is 1448409308
info: Time request is 1448409308
info: Time request is 1448409308
info: Time request is 1448409309
因此,基本上,您每秒只需要查询API 8次。为了实现这一点,你可以循环你的项目,并使用setTimeout在每1/8秒发出一个请求:
var delay = 1000 / 8;
objects.forEach(function(val, index) {
setTimeout(function() {
doSomething(index, val);
}, index * delay);
});
保持异步对于性能和反应性非常重要。它不应该阻止你做任何事情。
相关文章:
- esri javascript异步打印
- jQuery is not loaded
- AngularJS JSON not arriving php
- JavaScript异步问题
- $translateProvider.useStaticFilesLoader的Angular Translate异步定
- $rootScope not working
- reactRedux is not defined
- 异步facebook功能
- 异步并行错误
- 在Redux中,我应该在哪里编写复杂的异步流
- jQuery document.ready not working
- Javascript/Jquery Blob not showing Chrome PDF
- ReferenceError: not defined
- ReferenceError: cordova is not defined @ng-cordova.min.js:7
- Javascript getElementsByTagName not working?
- 角度异步http自动完成
- 如何从SeleniumWebdriver获取异步Javascript响应
- jQuery's trim()的前缀为not运算符
- 节点JS用于NOT异步
- 异步Javascript/async:应立即返回not interrupt函数