Home > Software design >  JS: awaited resolved promises come back wrapped in a promise that I cannot access
JS: awaited resolved promises come back wrapped in a promise that I cannot access

Time:09-03

I am ultimately pushing unresolved promises to be values of an object and then awaiting those to recall later:

let names = ["aaron", "bob", "john", "aaron"];
let allNames = {};

// just setting up my object with names as the key

names.forEach(name => {
   if (!allNames[name]) {
         allNames[name] = null;
   }
});

//iterating through and running async requests in parallel and storing the unresolved promises as the object value

let allDataForNamedPerson;

for (const [x] of names) {
   if (!allNames[name]) {
       allDataForNamesPerson = this.getNameData(name)// async api call
        
       allNames[name] = allDataForNamesPerson // storing the promise
   }
}

then I await until all these have resolves;

    await Promise.all([...Object.values(this.allNames)]);

my problem is that when I go to looking up one of the resolved values from the object, for example:

allNames["john"] , the value in console an Object wrapped in a promise:

promise {
   salary: 41992,
   position: clerk
}

so I cannot access it via allNames["john"].salary -- that comes back as undefined. What I doing wrong here?

CodePudding user response:

await doesn't replace promises with their values. If you want to work with the values, you have to grab them yourself:

  const resolvedValues = await Promise.all([...Object.values(this.allNames)]);

and then resolvedValues[someIndex] gives you unwrapped data.

Using bare await only guarantees that a given promise is settled in the code after the await line but the values are still wrapped.

  • Related