node.js服务器和AWS异步调用问题

时间:2017-09-21 07:22:56

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

我有一个简单的节点Express应用程序,它具有调用节点服务器的服务。节点服务器调用AWS Web服务。 AWS只列出它找到的任何S3存储桶,并且是异步调用。问题是我似乎无法让服务器代码“等待”AWS调用返回JSON数据并且函数返回undefined。

我在网上看过很多关于此的文章,包括承诺,等待等等,但我想我不理解这些工作的方式!

这是我的第一个节点曝光者,如果有人能指出我正确的方向,我将不胜感激?

以下是我的代码的一些片段......如果它有点粗糙,我会道歉但是我已经多次切碎并改变了事情!

Node Express;

var Httpreq = new XMLHttpRequest(); // a new request

Httpreq.open("GET","http://localhost:3000/listbuckets",false);
Httpreq.send(null);

console.log(Httpreq.responseText);

return Httpreq.responseText;  

节点服务器

app.get('/listbuckets', function (req, res) {

var bucketData = MyFunction(res,req);

console.log("bucketData: " + bucketData);

});

function MyFunction(res, req) {

var mydata;
var params = {};

res.send('Here are some more buckets!');

var request = s3.listBuckets();

// register a callback event handler
request.on('success', function(response) {
    // log the successful data response
    console.log(response.data);
    mydata = response.data; 
});

// send the request
request.
on('success', function(response) {
  console.log("Success!");
}).
on('error', function(response) {
  console.log("Error!");
}).
on('complete', function() {
  console.log("Always!");
}).
send();

return mydata;
}

2 个答案:

答案 0 :(得分:0)

使用最新的Fetch API(https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)进行HTTP调用。它内置了对Promise的支持。

fetch('http://localhost:3000/listbuckets').then(response => {
    // do something with the response here
}).catch(error => {
    // Error :(
})

答案 1 :(得分:0)

我最终得到了这个;

const request = require('request');

request(url, function (error, response, body) {

    if (!error && response.statusCode == 200) {

        parseString(body, function (err, result) {
            console.log(JSON.stringify(result));
        });

        // from within the callback, write data to response, essentially returning it.
        res.send(body);
    }
    else {
        // console.log(JSON.stringify(response));
    }
})