node express aws s3.listBuckets在呈现页面后执行回调

时间:2017-07-17 07:05:07

标签: node.js amazon-web-services amazon-s3

列出带回调的存储桶:

router.get('/', function(request,response) {
    s3.listBuckets(function(error, data) {
        if (error) {
            console.log(error);
        } else {  
            console.log(data.Buckets[0].Name);//since i have only one bucket
            bucket = data.Buckets[0].name;     
        }
    });

    response.render('index', { mybucket:bucket });
    console.log("rendered page");
});

输出:

rendered page                      //rendered page with mybucket:'' empty
GET /getbucket 200 7.827 ms - 787
lvresults                         //bucketname displayed after rendering in console
只有在呈现页面后才能访问

bucketname

1 个答案:

答案 0 :(得分:1)

您应该访问回调函数中的数据。

router.get('/', function(request,response) {
    s3.listBuckets(function(error, data) {
        if (error) {
            console.log(error);
        } else {  
            console.log(data.Buckets[0].Name);
            bucket = data.Buckets[0].name;  
            console.log("rendered page"); 
            response.render('index', { mybucket:bucket });         
        }
    });   

});

为了更好地了解异步行为,this link会有所帮助。