skip to Main Content

I have a somedataMap : Map<string, Promise<SomeData>> that I would like to populate.

I also have an async function async function getSomeData(someIdentifier:string): Promise<SomeData>, that I would like use as the values in that map

Obviously if I do something like somedataMap.set("someId", getSomeData("someId")), then the code in getSomeData is called, which I don’t want to do until maybe later. What is the best way to wrap/closure the getSomeData function as a Promise so I can store it or pass it to other functions?

2

Answers


  1. You can use either

    somedataMap: Map<string, () => Promise<SomeData>>
    
    somedataMap.set("someId", () => getSomeData("someId"))
    

    OR

    use it as it is, and later, when you want to receive value from Promise, do the following:

    await somedataMap.get("someId")
    
    Login or Signup to reply.
  2. Async functions always return promises. You don’t need to wrap it. Just call it.

    const getSomeData = async (id) => {
      return 'some data';
    };
    
    const somedataMap = new Map();
    
    getSomeData('x').then(data => {
    
      console.log(`data is "${data}"`);
    
      somedataMap.set("someId", data);
    
      console.log( somedataMap.values().next().value );
    
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search