-2

My fetch() is not working within my AWS Lambda when executed. I receive no data back from my fetch and nothing in Cloudwatch. I think my issue is the multiple async/await/promises. I'm unsure how the multiple promises work. Can someone help refactor these functions? Thanks!

Handler:

export async function consumer(event, context) {
    event.Records.forEach(async (record) => {
            const body = JSON.parse(record.body)
            api_url.searchParams.append("url", body.url)
          
            await callPSI(api_url.href)
    
        });
    
    }
  
export const callPSI = async (url) => {
 
    const url = "https://jsonmock.hackerrank.com/api/movies";

    fetch(url).then(res => {
        console.log("response: ", res)
        return res.json();
    }).then(data => {
        console.log('data: ', data);
    })

}
Trey Copeland
  • 3,387
  • 7
  • 29
  • 46
  • Try using map method instead of forEach. I think it will work. – Nithin K Joy May 17 '23 at 16:54
  • So no `console.log` prints? – Unmitigated May 17 '23 at 16:55
  • Consider using `map` as @NithinKJoy suggested in conjunction with the [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) API. A high level example would look like: `const promises = new Array(5).fill('').map((item, index) => new Promise((resolve) => resolve(index))); Promise.all(promises).then(result => console.log(result));` – digita1-anal0g May 17 '23 at 17:10
  • @digita1-anal0g could you please post how that would work in my situation? Im unable to get it working. – Trey Copeland May 17 '23 at 17:56

1 Answers1

0

Had to use Promise.all():

await Promise.all (

event.Records.map( async (record) => {
    const body = JSON.parse(record.body)
    api_url.searchParams.append("url", body.url)
    
    try {
        const resp = await fetch(api_url.href)
        const json = await resp.json()
        console.log(json)
    } catch (error) {
        console.log("error", error)
    }

})

)
Trey Copeland
  • 3,387
  • 7
  • 29
  • 46
  • Sorry for the delay. I saw your comment and was in the middle of fleshing something out for you, but I got pulled into a meeting. In any case, glad to see you got everything sorted out. – digita1-anal0g May 17 '23 at 19:17
  • @digita1-anal0g thanks for the help anyway! was happy i learned it on my own :) – Trey Copeland May 17 '23 at 19:20