reactjsarraystypescriptpromisepolkadot-js

React with Typescript Array of promises


I have the following function:

function queryProposals(hash:string) {

      let t = api?.query.backgroundCouncil.proposalOf(
        
        hash,(data1:any)=>{
        let data0 = data1.toPrimitive().args.account as InjectedAccountWithMeta;    
        let data = proposals;
        if (data0 && !data.includes(data0)){
          data.push(data0);                    
          dispatch1({type:`SET_PROPOSALS`,payload:data}); 
          //console.log(data)
          return data
        }        
      }
      );
      
      return t
    }


The commented console.log(data) will return the expected list of data, however, console.log(t) is always just return:[Promise,Promise,Promise,...]

below is the portion where I actually use the function and check the returned value as newl:

api.query.backgroundCouncil.proposals((hash: string[]) => {
      if (hash.length > 0) {
          let newl  = hash.map((x) => queryProposals(x)?.then(list => list));  
          console.log(newl);       
      }
});

I really don't know what to do, I am expecting the returned variable t to be the same as the returned variable data.

Thanks in advance

Kazu


Solution

  • Sounds like you want to use Promise.all. This function lets you turn an array of promises into an array of the promises' results.

    const someArrayOfPromises = [promise, otherPromise, otherPromise2];
    const arrayOfPromiseResults = await Promise.all(someArrayOfPromises);
    

    alternatively:

    const someArrayOfPromises = [promise, otherPromise, otherPromise2];
    Promise.all(someArrayOfPromises).then((arrayOfPromiseResults) => {
      handleResults(arrayOfPromiseResults);
    });