Home > other >  Sequential while mapping an array with promise in javascript
Sequential while mapping an array with promise in javascript

Time:12-08

I had to ask since I cannot find a decent way to solve it. I have follow tutorial from How to Resolve JavaScript Promises Sequentially (one by one) but still it cannot working on my situation after I alter it.

I have called a SQLite query to get data and get an array of data as response. Then I call the a function to start waiting the whole other process until this subprocess complete.

Sample resp: [{"TSTaskID": 1638938895}, {"TSTaskID": 1638945283}]

async function getUnsyncRecordFromLocal() {
   /// ... and the rest of the code send query to SQLite
   callTasks(resp);
}

  const callTasks = async (response) => {
    const allPromise = Promise.all(response.map(async (_item) => {
      task1(_item)
        .then((resp1) => task2(resp1))
        .then((resp2) => task3(resp2))
        .catch(console.error);
    }))

    const lists = await allPromise;

  }
  const task1 = async (TSTaskID) => {
    return new Promise((resolve, reject) => {
      console.log('task1 done.', TSTaskID);
      resolve(TSTaskID)
    })
    /** implementation */
  };

  const task2 = async (TSTaskID) => {
    return new Promise((resolve, reject) => {
      console.log('task2 done.', TSTaskID);
      resolve(TSTaskID)
    })
    /** implementation */
  };

  const task3 = async (TSTaskID) => {
    return new Promise((resolve, reject) => {
      console.log('task3 done.', TSTaskID);
      resolve(TSTaskID);
    })
    /** implementation */
  };

The log when doing this way

 LOG  task1 done. 1638938895
 LOG  task1 done. 1638945283
 LOG  task2 done. 1638938895
 LOG  task2 done. 1638945283
 LOG  task3 done. 1638938895
 LOG  task3 done. 1638945283

What I want it to look

 LOG  task1 done. 1638938895
 LOG  task2 done. 1638938895
 LOG  task3 done. 1638938895
 LOG  task1 done. 1638945283
 LOG  task2 done. 1638945283
 LOG  task3 done. 1638945283

I have try several way by using async function but the task still not complete in sequence. Like task 1, 2, 3 for same number, and next task with same number. Because I need to check with server database and the update the local SQLite table. So, it need to wait one to finish before continue with next.

CodePudding user response:

Both initial Promises of task1 will be fired when mapping. You need to wait for the first to be done before even starting the second. e.g.

const callTasks = async (response) => {
    const result = []
    for(let i = 0; i < response.length; i  ){
        const current = response[i]
        try {
            const result1 = await task1()
            const result2 = await task2(result1)
            const result3 = await task3(result3)
            result.push(result1)
        } catch(e) {
            // catch here
        }
    }
    return result
} 
  • Related