Austin Meyers
Austin Meyers

Reputation: 153

Can't I add static values to native javascript Promises?

I'm iterating through an array of objects to build a collection of Promises that I want to await in parallel. I need a specific property (unrelated to the promise) to persist in the result, but I can't just add it as a property of the Promise, it gets wiped away when the promise resolves:

let arrayOPromises = someArrayOfValues.map((promiseParams) => {
   let response = someFunctionThatReturnsAPromise(promiseParams);
   response.valueINeedToPersist = promiseParams.objectPropertyINeed; //unique to each iteration of map()
   return response;
});

await Promise.all(arrayOPromises);

// gives me the resolved promises, but not the added value

// [resolvedPromise1, resolvedPromise2];

// resolvedPromise1.valueINeedToPersist === 'undefined'

Upvotes: 2

Views: 267

Answers (1)

Bergi
Bergi

Reputation: 664990

I need a specific property (unrelated to the promise) to persist in the result

Yes, then do add it to the result and not to the promise object:

const arrayOPromises = someArrayOfValues.map(async (promiseParams, objectPropertyINeed) => {
   const response = await someFunctionThatReturnsAPromise(promiseParams);
//                  ^^^^^
   response.valueINeedToPersist = objectPropertyINeed;
   return response;
});

await Promise.all(arrayOPromises);

Upvotes: 3

Related Questions