npm mysql promise

Solutions on MaxInterview for npm mysql promise by the best coders in the world

showing results for - "npm mysql promise"
Alberto
07 Jan 2021
1This is gonna be a little scattered, forgive me.
2
3First, assuming this code uses the mysql driver API correctly, here's one way you could wrap it to work with a native promise:
4
5function getLastRecord(name)
6{
7    return new Promise(function(resolve, reject) {
8        // The Promise constructor should catch any errors thrown on
9        // this tick. Alternately, try/catch and reject(err) on catch.
10        var connection = getMySQL_connection();
11
12        var query_str =
13        "SELECT name, " +
14        "FROM records " +   
15        "WHERE (name = ?) " +
16        "LIMIT 1 ";
17
18        var query_var = [name];
19
20        connection.query(query_str, query_var, function (err, rows, fields) {
21            // Call reject on error states,
22            // call resolve with results
23            if (err) {
24                return reject(err);
25            }
26            resolve(rows);
27        });
28    });
29}
30
31getLastRecord('name_record').then(function(rows) {
32    // now you have your rows, you can see if there are <20 of them
33}).catch((err) => setImmediate(() => { throw err; })); // Throw async to escape the promise chain
34So one thing: You still have callbacks. Callbacks are just functions that you hand to something to call at some point in the future with arguments of its choosing. So the function arguments in xs.map(fn), the (err, result) functions seen in node and the promise result and error handlers are all callbacks. This is somewhat confused by people referring to a specific kind of callback as "callbacks," the ones of (err, result) used in node core in what's called "continuation-passing style", sometimes called "nodebacks" by people that don't really like them.
35
36For now, at least (async/await is coming eventually), you're pretty much stuck with callbacks, regardless of whether you adopt promises or not.
37
38Also, I'll note that promises aren't immediately, obviously helpful here, as you still have a callback. Promises only really shine when you combine them with Promise.all and promise accumulators a la Array.prototype.reduce. But they do shine sometimes, and they are worth learning.
similar questions
queries leading to this page
npm mysql promise