繁体   English   中英

AWS方法的Node.js forEach循环

[英]Node.js forEach loop of aws method

我正在尝试在forEach循环完成后执行代码,这是我的问题的简化版本:

var arr = { values: ['1', '2', '3', '4', '5'] };

arr.values.forEach(function (element) {
    ec2.describeInstances({ InstanceIds: ['i-51ec7d83'] }, function (err, data) {
        console.log(data.Reservations[0].Instances[0].Tags[0].Value);
    });
});

console.log('Excecute this after.');

但是结果是:

之后执行此操作。

测试1

测试1

测试1

测试1

测试1

我以为for每个循环都是同步的,为什么会这样呢? 我能做什么?

谢谢!

正如其他人已经提到的那样, ec2.describeInstances是异步的。

您需要知道所有异步调用何时完成。 为此,您可以使用Async.js之类的库。 这是一个例子:

var async = require('async');
var arr = { values: ['1', '2', '3', '4', '5'] };    

async.each(arr.values, function(element, callback) {
  ec2.describeInstances({ InstanceIds: ['i-51ec7d83'] }, function (err, data) {
    console.log(data.Reservations[0].Instances[0].Tags[0].Value);
    callback(); // <-- this lets it know the async operation is complete
  });
}, function() {
  console.log('Excecute this after.');
});

each方法的第三个参数是done回调,当循环中的所有异步调用done ,将调用该回调。

不幸的是,我无法发表评论,但是正如Chris Muench所说的,由于Array.prototype.forEachconsole.log是同步的, describeInstances可能是异步的。

根据AWS Docs:

All requests made through the SDK are asynchronous and use a callback interface. Each service method that kicks off a request can accept a callback as the last parameter with the signature function(error, data) { ... }. This callback will be called when the response or error data is available.

http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-making-requests.html https://nodejs.org/api/console.html#console_console

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM