skip to Main Content

I am trying to push functions into an array in JavaScript and then execute them using Promise.all(). However, I noticed that the functions are being immediately called when I push them into the array. How can I prevent the immediate execution of functions and ensure they are executed only when using Promise.all()?

Here’s a simplified example of my code:

export async function changePrices(id, prices, checkVariables) {
  let tasks = []

  tasks.push(changePrice(1, 1, 1, 1))
  tasks.push(changePrice(2, 2, 2, 2))
  tasks.push(changePrice(3, 3, 3, 3))
  tasks.push(changePrice(4, 4, 4, 4))

  console.log('tasks:', tasks);
  await Promise.all(tasks)
}

export async function changePrice(id, price, type, test) {
  console.log('start:', test);
  // Some asynchronous operations here
  console.log('end:', test);
  return 'helloooo'
}


 prices.map(price => {
    const minPrice = minPrices.find(_price => _price.TYPE === price.TYPE)
    if (minPrice) {
      secondTasks.push(changePrice(mainProduct.ID, minPrice.PRICE, minPrice.TYPE, 'second'))
    }
    firstTasks.push( changePrice(id, price.PRICE, price.TYPE, 'first'))
  })
  await Promise.all(firstTasks)
  await Promise.all(secondTasks)

2

Answers


  1. Parentheses cause a function to be executed. If you just want to store the function name you have to leave them out. Then, you’ll have to store the parameters as well. For example:

    tasks.push({callback:changeprice, params:[1,2,3,4]})
    

    Then later you can execute it using

    let task = tasks[0]
    task.callback(...task.params)
    
    Login or Signup to reply.
  2. In your code, the functions are immediately called and executed because you are invoking them directly when pushing them into the tasks array. To prevent immediate execution and ensure they are executed only when using Promise.all(), you need to pass the function references instead of invoking them.

    Example:

      let tasks = [];
    
      tasks.push(() => changePrice(1, 1, 1, 1));
      tasks.push(() => changePrice(2, 2, 2, 2));
      tasks.push(() => changePrice(3, 3, 3, 3));
      tasks.push(() => changePrice(4, 4, 4, 4));
    
      console.log('tasks:', tasks);
      await Promise.all(tasks.map(task => task()));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search