I'm trying to delete api keys using AWS SDK JS, but I'm receiving this error message:
{
"errorType": "Runtime.UserCodeSyntaxError",
"errorMessage": "SyntaxError: await is only valid in async function",
"stack": [
"Runtime.UserCodeSyntaxError: SyntaxError: await is only valid in async function",
" at _loadUserApp (/var/runtime/UserFunction.js:98:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:36:30)",
" at Module._compile (internal/modules/cjs/loader.js:701:30)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)",
" at Module.load (internal/modules/cjs/loader.js:600:32)",
" at tryModuleLoad (internal/modules/cjs/loader.js:539:12)",
" at Function.Module._load (internal/modules/cjs/loader.js:531:3)",
" at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)",
" at startup (internal/bootstrap/node.js:283:19)"
]
}
I've tried to create a promise to delete, just like I did to select keys, but I think it might be a problem to do it inside a foreach.
My code:
let sendPromise = null;
let params = {
includeValues: true,
limit: 500
};
let dados = null;
sendPromise = new AWS.APIGateway().getApiKeys( params ).promise();
try {
dados = await sendPromise;
} catch(err) {
console.error(err, err.stack);
return criarResposta( 500, `{
"message": "Erro interno"
}` );
}
dados.items.forEach( chave => {
const paramsDeletar = {
apiKey: chave.id
};
sendPromise = new AWS.APIGateway().deleteApiKey( params ).promise();
try {
let dadosDeletar = await sendPromise;
} catch(err) {
console.error( err, err.stack );
return criarResposta( 500, `{
"message": "Erro interno"
}` );
}
});
return criarResposta( 200, JSON.stringify( dados ) );
Other thing, do I need to wait for all my promises individually or there is a way of wait for promise's bundle? I can't not wait for my promise, because I'm using lambda, but I wish I could let them running together
Here you better replace the forEach loop with a for loop, that way will be able to use the await in it:
...
for (const chave of dados.items) {
const paramsDeletar = {
apiKey: chave.id
};
sendPromise = new AWS.APIGateway().deleteApiKey( params ).promise();
try {
let dadosDeletar = await sendPromise;
} catch(err) {
console.error( err, err.stack );
return criarResposta( 500, `{"message": "Erro interno"}` );
}
}