如何在Node.js中从AWS getObject调用中返回variables

我正在研究一个Node.js项目,它依赖于AWS​​的getObject响应。 目前,我可以访问我需要的数据并将其存储在variables( header )中,但不知道如何使其在主函数中可用。

 TileStreamerS3.prototype.Init = function(filepath, index, s3config){ var retval = false; AWS.config.update({accessKeyId: s3config.access_key, secretAccessKey: s3config.secret_key}); var blc = new BlockLibraryConfigs(); var awsConfig = blc.awsConfig; AWS.config.update({region: awsConfig.region}); var aws = new AWS.S3(); var params = { Bucket: s3config.bucket, Key: s3config.tile_directory + filepath, Range: 'bytes=0-27' }; aws.getObject(params, function(err, data){ if(err == null){ var header = bufferpack.unpack('<7I', data.Body); return header; } }); }; 

如何返回headervariables? 我看到了一个使用JQuery的可能的解决scheme,但是我在Windows上,并且遇到了JQuery使用Node的问题。 如果还有更好的办法,我不想走这条路。

更新:我知道有关于从asynchronous函数返回值有多个问题。 我觉得绊倒我的是, aws.getObject()是一个函数,将另一个函数作为参数。 我想从函数返回aws.getObject()函数参数的header值。 此外,我没有权限改变getObject()函数。

了解asynchronous编程的第一件事是,您不能将callback的结果实际返回到主函数或其他任何地方。 这是一个关于asynchronous编码的教程,以帮助您入门 。


至于你目前的情况,我会处理它使用asynchronous瀑布 。 Async会强制其他asynchronous函数在调用下一个函数(以前一个函数的输出作为下一个函数的参数)之前等待它们完成同步行为。

这里是一个例子:

 TileStreamerS3.prototype.Init = function(filepath, index, s3config, callback) { // pass a callback function as a parameter var retval = false; AWS.config.update({ accessKeyId: s3config.access_key, secretAccessKey: s3config.secret_key }); var blc = new BlockLibraryConfigs(); var awsConfig = blc.awsConfig; AWS.config.update({ region: awsConfig.region }); var aws = new AWS.S3(); var params = { Bucket: s3config.bucket, Key: s3config.tile_directory + filepath, Range: 'bytes=0-27' }; async.waterfall([function(callback) { aws.getObject(params, function(err, data) { if (!err) { var header = bufferpack.unpack('<7I', data.Body); callback(null, header); // using this we are passing the control to the // next function in the array } }); }, function(header, callback) { // this is the function which will be called // synchronously from aws.getObject's callback // use the header value passed from the previous function // do the next bit of asynchronous computation callback(null, output_if_any); // call the next function or the final callback }], callback); // attach the callback function to the async.waterfall // due to the async nature of the code, anything written after the waterfall will // be executed before the above code! So if you try to set any variable within the // async function's callback and console.log it here, you will get undefined. }; 

这里发生的事情是使用async.waterfall我们可以创build一个函数列表(每个函数可能包含asynchronous函数)被一个接一个地同步调用。 当所有的函数都被执行完后,最后的callback函数被调用,输出results

现在当你调用函数TileStreamerS3.Init ,你可以这样做:

 TileStreamerS3Object.Init(filepath, index, s3config, function(err, results) { if (err) { // handle the error } else { // do whatever you want with the results // and continue the processing } });