skip to Main Content

I would like to create multiple functions dynamically and run them in parallel.

The starting point is an array containing several strings. These strings are to serve as input for the functions. There are exactly as many functions as the length of the array.

Unfortunately, my code is not quite working yet and I did not know how to fix the issue.

TS2345: Argument of type ‘Promise’ is not assignable to parameter of type ‘(data: string) => Promise’.   Type ‘Promise’ provides no match for the signature ‘(data: string): Promise’.

How can I push the function into the list so that later the return value ends up in the data?

  private async runParallel() {
        let listOfFunctions: ((data: string) => Promise<string>)[] = [];

        let outline: string[] = ["test1", "test2", "test3"]

        for (let i = 0; i < outline.length; i++) {
            let func = async (input: string): Promise<string> => {
                // run async/await calls...
                return input;
            };

            // TS2345: Argument of type 'Promise<string>' is not assignable to parameter of type '(data: string) => Promise<string>'.   Type 'Promise<string>' provides no match for the signature '(data: string): Promise<string>'.
            listOfFunctions.push(func(outline[i]));
        }

        const data = await Promise.all(listOfFunctions);

        console.log(data);
    }

2

Answers


  1. To fix this, you need to change the function to return a promise instead of a value. You can do this by using the async and await keywords.

    async function runParallel() {
      let listOfFunctions: ((data: string) => Promise<string>)[] = [];
    
      let outline: string[] = ["test1", "test2", "test3"]
    
      for (let i = 0; i < outline.length; i++) {
        let func = async (input: string): Promise<string> => {
          // run async/await calls...
          return await Promise.resolve(input);
        };
    
        listOfFunctions.push(func);
      }
    
      const data = await Promise.all(listOfFunctions);
    
      console.log(data);
    }
    Login or Signup to reply.
  2. Because your already executing the function ->

    func(outline[i])
    

    Your not returning a function that returns a Promise to a string, your just pushing a Promise for a string into the array.

    So the fix is just to remove the function part from your array.

    eg..

    let listOfFunctions: (Promise<string>)[] = [];
    

    IOW: Your function bit is already done before it’s placed into the array, don’t worry though, this will still execute in parallel.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search