【问题标题】:node.js server and AWS asynchronous call issuenode.js 服务器和 AWS 异步调用问题
【发布时间】:2018-03-02 10:40:13
【问题描述】:

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

我在网上阅读了很多很多关于此的文章,包括承诺、等待等,但我认为我并没有完全理解这些工作的方式!

这是我第一次接触节点,如果有人能指出我正确的方向,我将不胜感激?

这是我的代码的一些 sn-ps...抱歉,如果它有点粗糙,但我已经多次修改和更改了!

节点快递;

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;
}

【问题讨论】:

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


【解决方案1】:

使用最新的 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 :(
})

【讨论】:

    【解决方案2】:

    我最终得到了这个工作;

    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));
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 2011-10-08
      • 2013-05-15
      • 2018-02-09
      • 2023-03-04
      • 2012-05-11
      • 2013-03-25
      • 2015-02-19
      • 1970-01-01
      相关资源
      最近更新 更多