Leveraging Promises to Process MySQL Return Values in Node.js
In transitioning from Python to Node.js, the asynchronous nature of Node.js can present challenges. Consider a scenario where you need to return a value from a MySQL function, such as getLastRecord(name).
Traditionally, Node.js uses callbacks for asynchronous operations. However, to handle the asynchronous nature of getLastRecord(), we'll leverage Promises.
To implement the function using a Promise:
function getLastRecord(name) { return new Promise((resolve, reject) => { // Setup MySQL connection and query // ... connection.query(query_str, query_var, (err, rows, fields) => { if (err) { return reject(err); // Handle error } resolve(rows); // Resolve with results }); // Callback function }); }
To handle the returned value, you can chain .then() and .catch() callbacks to the Promise:
getLastRecord('name_record') .then((rows) => { // Handle returned rows here console.log(rows); }) .catch((err) => { // Handle errors here console.log(err); });
You can also implement the conditional check:
getLastRecord('name_record') .then((rows) => { if (rows.length > 20) { console.log('action'); } });
By adopting Promises in this scenario, you introduce a more structured and readable approach to handling asynchronous operations, ensuring a cleaner and more maintainable codebase.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3