我的兰卜达函数为Pets预呈现一个反应用户界面.它由API网关端点调用。我正在从cra-无服务器项目中调整这个项目。我使用的NodeJS服务器框架是Koa。我创建了一个异步handler
函数来响应客户端请求。它做了三件事:
getCatsResponse
。getCatsResponse
对象呈现UI。我注意到,这使得我的请求需要很长时间才能得到答复,我想这个问题有点开放,但我希望得到以下三点的澄清:
Promise.all()
函数创建的Promise
列表中删除Promise
时,没有将这些项插入到表中呢?Promise
来解决,我应该把这个责任委托给另一个Lambda函数吗?await
来解决它),对吗?ctx.body
时,这个响应只在Lambda到达函数结束时发送,对吗?import koa from 'koa'
import http from 'koa-route'
import serve from 'koa-static'
import App from '../src/App'
import { paths } from './config'
import { render } from './lib/render'
import AWS from 'aws-sdk'
import GetCatsResponse from '../typings/GetCatsResponse'
import fetch from 'node-fetch';
import { Cat } from '../typings/Cat'
export const Router = new koa()
const DynamoDB: AWS.DynamoDB = new AWS.DynamoDB();
const handler = async (ctx: koa.Context) => {
// Try Pet API
let url = 'https://api.pets.com/v2/cats'
let getCatsResponse: GetCatsResponse = Object.create(GetCatsResponse);
await fetch(url).then((response: any) => response.json().then((jsonData: any) => {
getCatsResponse = jsonData;
}));
console.log(getCatsResponse);
// Render response body
ctx.body = render(getCatsResponse, App, ctx.request.path)
// Enter item into DynamoDB
return Promise.all(getCatsResponse.items.map((catResponse) => {
const input: AWS.DynamoDB.PutItemInput = Cat.toDynamoDBTableItemInput(catResponse)
console.log(input);
return DynamoDB.putItem(input).promise()
.then(() => {
console.log('Inserted cat ID ' + catResponse.cat_id.toString());
})
.catch((err) => {
console.error(err);
});
}))
}
Router.use(http.get('/', handler))
Router.use(http.get('/index.html', handler))
Router.use(serve(paths.assets))
Router.use(http.get('*', handler))
发布于 2020-08-27 20:22:43
render
通常做什么,或者它在Lambda上是如何表现的。但是,如果您担心呈现会“停止”所发生的操作,则可以执行类似以下操作的操作,这样做的额外好处是按照操作的顺序(get the cats, THEN write them to DB, THEN return the body
)更显化。// Try Pet API
await fetch(url)...
// Enter item into DynamoDB
await Promise.all(...)
// Render response body
ctx.body = render(getCatsResponse, App, ctx.request.path)
https://stackoverflow.com/questions/63621830
复制相似问题