Callback on returned promise chain runs before callbacks in the aforementioned promise chain

74 views Asked by At

Context: Codebase I'm working in is a mixture of ES5 and ES6 thanks to babel.

I'm trying to accomplish waiting on a promise (returned by an async function in ES6 code) using .then() (in ES5 code).

Here's the async function I'd like to wait on:

static async getSignatureEntities(itemsRequireSignature) {
    const signatureEntities = [];
    if (itemsRequireSignature.length > 0) {
        const chunkSize = 50; //prevent url from getting too long
        const truncatedItemsRequireSignature = //something

        for (const items of truncatedItemsRequireSignature) {
            if (items.length > 0) {
                let page = 1;
                let filter = "sig"
    
                await populateSignatureEntitiesByPageAndFilter(page, filter, signatureEntities);
            }
        }
    }
    return signatureEntities;
}

Here's the promise chain I'm returning (in ES5 code) in getHistoryItems()

return getSignatureEntities(items)
         .then(function(signatureEntities) {
              return setUpFormResponseView() //callback 1
         .then(function(response) {
              return response[0].Data; //callback 2
          });

And here's where this returned chain is being waited on

return getHistoryItem()
    .then(callback3)

What should happen is callback 1 and 2 should run before 3, but what's happening is callback 3 is running before any of them, and the response value passed to callback 3 is a pending promise when it should be a value. It seems like getHistoryItems returns a resolved promise before the promise chain is actually resolved.

When stepping through the transpiled code, the async function returns at the await call and callback 3 starts executing, after which the async function resumes, and subsequently callbacks 1 & 2 execute after the function returns (which works as it should).

0

There are 0 answers