0

I have this code below in which I'm trying to return an array of objects with the following attributes:

0: {name: "Timmy", childID: "1", parentName: "Sally"}
1: {name: "Tommy", childID: "2", parentName: "Sully"}
2: {name: "Tammy", childID: "3", parentName: "Steve"}

Instead I am getting this:

0: {name: "Timmy", childID: "1", parentName: Promise}
1: {name: "Tommy", childID: "2", parentName: Promise}
2: {name: "Tammy", childID: "3", parentName: Promise}

I am trying to use the child ID to call the API and use the childID to a get a the name of a parent. I've tried using promise.resolve, promise.all, etc. I'm confused because res is of type string however when I call my convert function and log the array the attribute value of parent is always Promise and not the string value of the promise. Shouldn't the .then() method take care of that?

What am I doing wrong?

Any help is appreciated. Thank you!!!

  const namesAndIDs = allUsers.map(({ name, childID }) => ({name, 
  childID}));

  console.log("name and child IDs", namesAndIDs);

  const convert = async (childID: string) => {
    const parent = await APIclient.parents.findOne({id: childID})
    // console.log(typeof parent.name)
    return parent.name as string;
  }

   const x = namesAndIDs.map(obj => ({ ...obj, parentName: 
    Promise.resolve(convert(obj.childID!).then((res) => {
    console.log(res); return res}))
}
));
helloWorld
  • 135
  • 3
  • 13
  • Use `Promise.all` instead, to wait for each Promise to resolve before returning the new object – CertainPerformance Feb 17 '21 at 20:12
  • "Shouldn't the .then() method take care of that?" - no, a call to a promise's `then` method always returns a promise. Overall you can never get the result of a promise synchronously. See this [canonical question](https://stackoverflow.com/q/14220321/5217142) about processing results obtained from an asynchronous API. – traktor Feb 18 '21 at 02:29

0 Answers0