如何在AWS Lambda中执行return语句之前等待forEach循环完成?
# @param A : list of list of integers
# @return the same list modified
def rotate(A):
for row in range(len(A) // 2):
for col in range(row, len(A)-1 - row): # First col already takes care of last.
r = row
c = col
tmp1 = A[r][c]
while True:
next_r = c
next_c = len(A) - 1 - r
tmp2 = A[next_r][next_c]
A[next_r][next_c] = tmp1
if next_r == row and next_c == col:
break
tmp1 = tmp2
r = next_r
c = next_c
return A
答案 0 :(得分:1)
您已经在使用异步,因此请使用map返回承诺列表,并通过Promise.all()
等待所有承诺:
module.exports.shipments = async (event) => {
const axios = require("axios");
let data = JSON.parse(event.body);
let url = data.apiURL + "/api/1.1/wf/bulkshipments/initialize";
let patchURL = data.apiURL + "/api/1.1/obj/company/" + data.companyID;
let promises = data.shipments.map(item =>
axios.post(url, {
batchID: data.batchID,
companyID: data.companyID,
shipment: item})
})
);
await Promise.all(promises);
return {
statusCode: 200,
body: JSON.stringify({
message: 'Created successfully!',
totalShipments: data.shipments.length,
}, null, 2),
};
};
要等待每个呼叫,而不是同时触发所有发帖请求,请使用for...of loop:
module.exports.shipments = async (event) => {
const axios = require("axios");
let data = JSON.parse(event.body);
let url = data.apiURL + "/api/1.1/wf/bulkshipments/initialize";
let patchURL = data.apiURL + "/api/1.1/obj/company/" + data.companyID;
for (let item of data.shipments) {
await axios.post(url, {
batchID: data.batchID,
companyID: data.companyID,
shipment: item})
});
}
await Promise.all(promises);
return {
statusCode: 200,
body: JSON.stringify({
message: 'Created successfully!',
totalShipments: data.shipments.length,
}, null, 2),
};
};