I am refactoring some code that was using a Promise-Mysql library. I am now porting it to Mysql2 library. So far so good but I need help on a piece of code that is working with promises (I am not yet so good with promises).
The original code:
Promise.all([
db.query("UPDATE gantt_tasks SET text = ?, start_date = ?, duration = ?, progress = ?, parent = ? WHERE id = ?",
[task.text, task.start_date, task.duration, task.progress, task.parent, sid]),
updateOrder(sid, target)
])
.then(function (result) {
sendResponse(res, "updated");
})
.catch(function (error) {
sendResponse(res, "error", null, error);
});
});
has become:
con1.execute("UPDATE gantt_tasks SET text = ?, start_date = ?, duration = ?, progress = ?, parent = ? WHERE id = ?",
[task.text, task.start_date, task.duration, task.progress, task.parent, sid], function (err, result, fields) {
//if (err) throw err;
if (err) { sendResponse(res, "error", null, error); }
updateOrder(sid, target);
sendResponse(res, "updated");
});
sendResponse is the following:
function updateOrder(taskId, target) {
var nextTask = false;
var targetOrder;
target = target || "";
if (target.startsWith("next:")) {
target = target.substr("next:".length);
nextTask = true;
}
return db.query("SELECT * FROM gantt_tasks WHERE id = ?", [target])
.then(function (result) {
if (!result[0])
return Promise.resolve();
targetOrder = result[0].sortorder;
if (nextTask)
targetOrder++;
return db.query("UPDATE gantt_tasks SET sortorder = sortorder + 1 WHERE sortorder >= ?",[targetOrder])
.then(function (result) {return db.query("UPDATE gantt_tasks SET sortorder = ? WHERE id = ?",[targetOrder, taskId]); });
});
}
My question is: how do I change the return Promise.resolve();? In my code there is not a promise anymore...
Modernized:
asyncfunctions always return a promise, so this also fulfills your original requirement.You should probably use a transaction for this though.