Hello. I am trying to make an API that returns all the emails of members subscribed to a particular pricing plan. Below is my code which first gets all the orders and then for each order gets the member email. This code runs perfectly fine if I try it in $w.on Ready(function ()). But when I try the same code in an API it somehow doesnt wait for the promise to finish and returns nulls instead
const myListOrdersFunction = require('backend/test').myListOrdersFunction;
const myGetMemberFunction = require('backend/getMember').myGetMemberFunction;
$w.onReady(function () {
const response = {
"headers": {
"Content-Type": "application/json"
}
};
return test()
.then(result => {
console.log("final", result);
console.log("Type of result:", JSON.stringify(result));
response.body = {
"emails": result
};
//return ok(response);
console.log("response", response);
})
.catch(error => {
console.log(error);
});
});
async function test() {
return new Promise((resolve, reject) => {
const promises = [];
myListOrdersFunction()
.then(listedOrders => {
const emailPromises = listedOrders.map(order => {
const loginEmails = [];
return myGetMemberFunction(order.buyer.memberId)
.then(member => {
loginEmails.push(member.loginEmail);
return loginEmails;
})
.catch(error => {
console.log(error);
});
});
Promise.all(emailPromises)
.then(results => {
const flattenedEmails = results.flat();
resolve(flattenedEmails);
})
.catch(error => {
console.log(error);
reject(error);
});
})
.catch(error => {
console.log(error);
reject(error);
});
});
}
output from API
{"emails":"[null,null]"}
output if I run it in some page
final
Array(2)jsonTableCopy JSON
0: "premium2@g mail. com"
1: "amna.ahmad.ch@ gmail. com"
What am I doing wrong. Plz help