I've wasted two days trying to find an answer to this. I have reduced my code to mostly pseudo code for simplicity.
I need to have an async function that is called as a trigger from an SQS queue. The code loops through the 10 SQS records sent and for each it calls Twilio and uses the promise format. I want to build an array during this process so that at the end I can do a batch write to DynamoDB.
I can't figure out how to maintain/add to an array inside of the Twilio promise THEN that is readable outside/later.
exports.handler = async function(event, context) {
let messages = [];
//LOOP THROUGH SQS RECORDS
event.Records.forEach(record => {
//QUERY DYNAMO FOR DUPLICATES
//IF NOT A DUPLICATE
twilio.messages.create({
body: event.text,
to: event.phone,
from: '+15005550006'
})
.then((message) => {
//ADD MESSAGE TO STATUS SQS
//CREATE ARRAY FOR ENTRY INTO DYNAMODB BATCH WRITE
var item = {
PutRequest: {
Item: {
'msgid': { S: msgid },
'text': { S: text },
'phone': { S: phone },
'date': { S: now }
}
}
};
});
//END IF NOT A DUPLICATE
});
//BATCH WRITE TO DYNAMO OF ALL ITEMS IN MESSAGES ARRAY
};
EDIT: This is the actual code based on suggestions. Nothing is logged on either console.log, not even the "message". Currently just trying to get anything from then to be returned in Promise.all. Actually need to return the messages array but trying to get SOMETHING to return.
let messages = [];
var messagePromises = event.Records.map(record => {
var text = record.body;
var phone = record.messageAttributes["phone"].stringValue;
var msgserviceid = record.messageAttributes["msgserviceid"].stringValue;
var userid = record.messageAttributes["userid"].stringValue;
var credits = record.messageAttributes["credits"].stringValue;
var item = [];
var payload = {
"phone": phone,
"text": text,
"msgserviceid": msgserviceid
};
return twilio.messages.create({
body: text,
to: phone,
from: '+15005550006'
}).then((message) => {
var msgid = message.sid;
var now = new Date().toISOString().slice(0, 19).replace('T', ' ');
var item = {
PutRequest: {
Item: {
'msgid': { S: msgid },
'text': { S: text },
'phone': { S: phone }
}
}
};
messages.push(item);
console.log("message", message);
return message;
}).catch((error) => {
console.log("error", error);
});
});
Promise.all(messagePromises).then((values) => {
console.log(values);
});
};```
question from:
https://stackoverflow.com/questions/65600579/variables-inside-of-lambda-promise-inside-of-async-function-w-promise-all 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…