Search code examples
javascriptnode.jses6-promise

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'

Solution

  • 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);