使用来自aysnc Javascript HTTP请求的数据? (无服务器)

时间:2018-11-29 01:45:37

标签: javascript node.js asynchronous aws-lambda serverless

我正在使用nodejs无服务器模块来创建lambda aws函数。

'use strict';
const request = require('request');
const options = {
  url: 'https://api.mysportsfeeds.com/v2.0/pull/nfl/2018-regular/games.json',
  method: 'GET',
  headers: {
    "Authorization": "Basic " + Buffer.from("1da103" 
+ ":" + "MYSPORTSFEEDS").toString('base64')
  }
}

//this is automatically called by aws
module.exports.hello = async (event, context) => {
  let result;
  request.get(options, (error, response, body) => {
    result = JSON.parse(body).lastUpdatedOn; //never happens cuz of async
  });
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: result,
    }),
  };
};

我遇到的问题是我无法从get请求返回输出,因为对结果变量的分配(在异步get请求中)发生在return语句之后。我认为我不能将外部函数转换为get请求的回调函数。我该如何解决?

1 个答案:

答案 0 :(得分:1)

另一种选择是提取请求逻辑并将其放入新函数中。

请记住,您需要捕获所有错误,因此请使用try-catch块来完成此操作。

'use strict';
const request = require('request');
const options = {
    url: 'https://api.mysportsfeeds.com/v2.0/pull/nfl/2018-regular/games.json',
    method: 'GET',
    headers: {
        "Authorization": "Basic " + Buffer.from("1da103"
            + ":" + "MYSPORTSFEEDS").toString('base64')
    }
};

function getResult() {
    return new Promise(function (resolve, reject) {
        request.get(options, (error, response, body) => {
            if (error) return reject(error);
            resolve(JSON.parse(body).lastUpdatedOn); //never happens cuz of async
        });
    });
}

//this is automatically called by aws
module.exports.hello = async (event, context) => {
    let result = await getResult();
    return {
        statusCode: 200,
        body: JSON.stringify({
            message: 'Go Serverless v1.0! Your function executed successfully!',
            input: result,
        }),
    };
};