Search code examples
javascriptmysqlnode.jspromisees6-promise

How can I use promise.all using mysql insert to cascade style?


I want to insert data 3 table using promise and I have a problem.I want to insert data in tasks table,get result insert id,insert that id in other table and get this insert id,insert that id other table.I want do that using Promise.all function.This is my code.

addClientTable(insertTask)
    .then(client_res => {
        return client_res.insertId;
    })
    .then(clientInsId => {
        insertTask.task.client_id = clientInsId;
        addTaskTable(insertTask)
            .then(task_res => {
                if (insertTask.task.connection == 0) {
                    updateTaskConnection(task_res.insertId)
                        .then(res => {
                            console.log(res);
                        })
                        .catch(err => {
                            console.log(err);
                        })
                }
                return task_res.insertId;
            })
            .then(taskInsId => {

                addTaskUsersTable(user_ids, taskInsId, clientInsId)
                    .then(result => {
                        resolve(result);
                    })
            })
            .catch(err => {
                reject(err);

            })
    })
    .catch(err => {
        reject(err);
    });

Solution

  • i don't see the need for Promise.all but for cleaner code and avoiding nested .then() , i would suggest async/await , the sugary syntax for promises, your code should look like :

    async function myFn (){
      const clientInsId = await addClientTable(insertTask).insertId;
    
      insertTask.task.client_id = clientInsId;
    
      const task_res = await addTaskTable(insertTask);
      let res;
    
      if (insertTask.task.connection == 0) {
        res = await updateTaskConnection(task_res.insertId);
        console.log(res);
      }
    
      const result = await addTaskUsersTable(user_ids, taskInsId, clientInsId);
    
      return result;
    };
    
    myFn()
      .then(data => console.log(data))
      .catch(err => console.log(err))