0

I am new to js async/await. I am using $.each utility and I found that the lines of code is getting executed async manner even after using await so, I switched from $.each -> for, that works for me

hitendra
  • 159
  • 2
  • 9
  • 2
    return the promise ... i.e `return fetch(url, {` - however, using async/await as a callback to `$.each` has the same pitfalls as it does in using it `.forEach` ... the TLDR of that is ... don't do that, use regular for loops (all the way up the nested loops you have) - see https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Jaromanda X Jun 28 '21 at 10:59

1 Answers1

3

You have await nested in some $.each(ticketIds, async function loops, but realise that these async functions return when they encounter an await, returning a promise: the loop will thus produce a set of promises and continue without awaiting those promises.

One of the simplest solutions is to use for loops, so that all the await expressions run in the context of the outer async function.

So for instance, change this:

$.each(rowGroups, function(serviceName, obj) {
    // ...
});

to this:

for (let [serviceName, obj] of Object.entries(rowGroups)) {
    // ...
}

...and do this for all those nested loops.

There is, I think, one instance where the iteration is not over a plain object, but over an array, so then change from this:

$.each(issueLinks, function(index, issue) {

to this:

for (let [index, issue] of issueLinks.entries()) {

This solves your problem. But as noted in comments, you also have another issue: createJiraResponse will remain undefined, because your client function does not return the promise. So either remove the braces from that arrow function, or change fetch( to return fetch(.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • of course, `const client` should **return** a promise too – Jaromanda X Jun 28 '21 at 11:12
  • Thanks for the response, I am trying this rn but when the `const client` return a promise. I need to make sure all the promises are resolved before executing the last line of code which is a POST request using `payload` – hitendra Jun 28 '21 at 11:14
  • @hitendra, that is indeed the purpose of replacing all your `$.each` loops with `for` loops. Then the last line will only execute when all the awaited promises have resolved. – trincot Jun 28 '21 at 11:16
  • And then Jaromanda's comment is also true: `client` currently does not return anything, so you must fix that any how (added a paragraph about that to my answer). – trincot Jun 28 '21 at 11:17