添加回调异步方法的返回值以编写HTTP响应。异步回调页面在写入响应之前完成加载

时间:2018-05-30 13:39:37

标签: node.js amazon-s3

我正在尝试使用NodeJS服务器应用获取AWS S3存储桶文件(对象)名称列表并作为HTTP响应文本返回。

下面是我写的完整代码。

var AWS = require('aws-sdk');
var http = require("http");

function onRequest(request, response) {
    response.writeHead(200, {
        'Content-Type': 'application/json'
    });
    var credentials = new AWS.SharedIniFileCredentials();
    AWS.config.credentials = credentials;
    AWS.config.logger = console;
    var str = "";
    var s3 = new AWS.S3();
    var params = {
        Bucket: 'bucketname',
        Delimiter: '/',
        Prefix: 'path/to/the/folder'
    }
    //var data = s3.listObjectsV2(params);   returns data as [object Object]

    s3.listObjects(params, function(err, data) {
        console.log("Data : " + data);
        for (var i = 0; i < data.Contents.length; i++) {
            var tokens = data.Contents[i].Key.split("/");
            str = str + tokens[tokens.length - 1];
            if (i != data.Contents.length) {
                str = str + ",";
            }
        }
        console.log("Final text:" + str);
    });

    response.write(str);
    response.end();
}

http.createServer(onRequest).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');'

问题:由于异步调用listObjects,我的HTTP响应写入在获得回调值之前就结束了。

任何人都可以帮助我使其同步,以便我可以添加str作为回复正文的一部分吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

你可以把res.write和res.end放在可以工作的回调中:

var AWS = require('aws-sdk'); var http = require("http");
function onRequest(request, response) { 
    response.writeHead(200, { 'Content-Type': 'application/json' }); 
    var credentials = new AWS.SharedIniFileCredentials(); 
    AWS.config.credentials = credentials; 
    AWS.config.logger = console; 
    var str = ""; 
    var s3 = new AWS.S3(); 
    var params = { Bucket: 'bucketname', Delimiter: '/', Prefix: 'path/to/the/folder' } 
    //var data = s3.listObjectsV2(params); 
    returns data as [object Object]

    s3.listObjects(params, function(err, data) {
        console.log("Data : " + data);
        for (var i = 0; i < data.Contents.length; i++) {
            var tokens = data.Contents[i].Key.split("/");
            str = str + tokens[tokens.length - 1];
            if (i != data.Contents.length) {
                str = str + ",";
            }
        }
        console.log("Final text:" + str);

        response.write(str); // And putting response write() and end() here
        response.end();
    });

    // taking off write() and end() from here

}

http.createServer(onRequest).listen(8081); 
console.log('Server running at http://127.0.0.1:8081/');

答案 1 :(得分:0)

您只需要response.end(str),它可以在内部回调。节点将保持HTTP流打开,直到S3调用返回。