0

The function below is supposed to return an array of objects. translationByLang is returning a Promise stored then in the "result" variable. In order to map my "result" I am using Promise.all to push the values to myArray but when I console.log the value of myArray I still have an array of Promises. Note that if I console log the response inside await Promise real data are shown, not Promise data...

async function getData() {

    let translationByLang = Object.values(translationArray.reduce((acc, 
     {field,lang,text}) => {
      acc[lang] = acc[lang] || {lang}
      acc[lang][field] = text
      return acc
    },{}))

    let result = translationByLang;

    if(result.length < 2){
      let obj = {"lang":"en", "name":"Documento mancante","pdf_url":""}
      result.push(obj)
    }

    let myArray=[]
    await Promise.all(result).then(res => {
      myArray.push(res)
    });
    return myArray

  }


Here is a screenshot that explains the whole thing. enter image description here

  • 1
    "*The function below is supposed to return an array of objects*" - it cannot. It's asynchronous. The best it can do is return a promise for the array of objects. – Bergi Nov 25 '22 at 10:34
  • What you need to change is `const arr = await getCorrectArray()`. – Bergi Nov 25 '22 at 10:36
  • You should `.then` on getData to have the correct array – Marios Nov 25 '22 at 10:38
  • 3
    You either use `.then` or `await` - don't combine them. I don't even understand why this is an `async` function, `result` does not seem like a Promise to me. Create an example repo/fiddle that we can run ourselves, it'll be easier to debug. – AbsoluteZero Nov 25 '22 at 10:38
  • 1
    async function was not needed. Thanks for your help. My understanding of async /await is still poor – beginnerspirit Nov 25 '22 at 12:46

0 Answers0