0

I am currently working in Ext JS, although that really should not matter. The code is simple: I have myFunc which constructs a myArray. Using forEach to loop through myArray, I call getDescription on each array element. getDescription is an async function that triggers an API call to get some resource.

elementDescription - the result of calling getDescription on each element of myArray ends up being a

Promise {<pending>} __proto__: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: "correct value from the API"

I'm quite new to promises, and I feel like the nested forEach along with the async syntax is somehow screwing with the code.

My code is as follows:

myFunc: function() {
    //some initial procedures 

    myArray.forEach(element => {
        var elementDescription = getDescription(element.Property).then(function(result) {return result})
        console.log(elementDescription)
    })

    // some more procedures
}

getDescription: async function (elementProperty) {
    var description = ""
    var apiResponse = await someWayToTriggerGetRequest()
    apiResponse.forEach(item => {description += item.content)
    return description;
}

What is going on? Why am I getting a pending promise?

Etfrerrr
  • 89
  • 2
  • 8
  • `then` returns the result wrapped in a promise: `elementDescription` is also a promise. You need to do `elementDescription.then(data => console.log(data)` to see *fulfilled* response. – adarsh Jun 14 '21 at 19:30
  • I see; yes, using `elementDescription.then(data => console.log(data)`, I can see the data. But could I set `elementDescription` to `data`? I tried ` elementDescription.then(data => { if (data) { elementDescription = data; } }` But it does not work... – Etfrerrr Jun 14 '21 at 19:49

0 Answers0