gpt4 book ai didi

javascript - 使用来自异步 Javascript http 请求的数据? (AWS无服务器)

转载 作者:行者123 更新时间:2023-12-03 00:39:07 26 4
gpt4 key购买 nike

我正在使用 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 请求的回调函数。我该如何解决这个问题?

最佳答案

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

请记住,您需要捕获任何错误,因此请使用 try-catch block 来执行此操作。

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

关于javascript - 使用来自异步 Javascript http 请求的数据? (AWS无服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53530679/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com