Search code examples
javascriptjqueryasync-awaitfetch

How to wait for promise to get resolve and execute other lines of code after


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


Solution

  • 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(.