How can I call an async function inside a loop


#1

My skill uses various API endpoints. The response of such an endpoint includes a user_id. There is another endpoint which retrieves user detail by user_id.

My intention is to fetch the the user detail by calling the corresponding endpoint inside a loop.

const result = await custom.get_email_clicks(emailId);

for(let i = 0; i < result.data.records.length; i++){
     const r = records[i];
     const user_id = r.data.user_id;
     
    // here I want to call the other API which gets me user detail.
    const user = await custom.get_user_detail(user_id);
    speech+= user.data.firstName + '  ' + user.data,lastName;
}

//output all user names
this.tell(speech);

The avobe approach gives me the following error:

There was a problem with the requested skill’s response

Probably this is not the right way to accomplish what I am trying to. Please let me know if there is a way to achieve the same.


#2

hi, i suggest you to not call api-s in loop,
i think a better solution is to call an api, and loop logic in server.


#3

Thanks @florijan.allaraj but the problem is I have no control over the APIs since its already built. I am only able to consume those endpoints! :slight_smile:

And looks like there is no real and option to accomplish what I am trying, right?


#4

Hi @emfluenceindia, one problem this approach could cause is that await custom.get_user_detail(user_id); in combination with the for-loop takes so much time that Alexa expects a response when your code is not finished, resulting in a problem with the skills’s response. Could you please verify that by logging the time it takes for the whole process to finish? If this is the case, you could use Progressive Responses for that, which basically means that Alexa will receive a response from your skill, while an operation is still going, and then receiving another response, once said operation is done.


#5

I will look into Progressive Response. This sounds promising :slight_smile:


#6

I tried Progressive Response but it didn’t help accomplishing my objective. I started a thread in StackOverflow today and got a number of responses there. Tried them all, but still no luck. I badly need your help!!

Here is the thread: