I want to create an ID for my program. The ID is random, but I must make sure that it not already exists in database. To do so, I search the ID, and if the search result is empty, then the ID passes, but if the search finds something, the process needs to start over.
In PHP I can do this logic for my code:
require('somesqlconnection.php'); $repeat = false; do { $id = createId(50); // this is my function for creating random with 50 as length for the string $result = mysqli_query("SELECT * FROM users WHERE id = '$id'", $conn); $repeat = mysqli_num_rows($result) > 0; } while ($repeat); echo $id;
How can I implement the same logic in node.js that is basically executing in asynchronous?
I tried this but didn’t work:
const util = require('util'); const sql = require('../sqlconnection.js'); let repeat = false; const query = util.promisify(sql.query).bind(sql); do { let id = createId(50); (async () => { const rows = await query(`SELECT id FROM users WHERE id = '${id}'`); repeat = rows.length > 0; })(); } while(repeat); console.log(id);
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You could create a function that returns a promise for a new ID like this:
const util = require('util'); const sql = require('../sqlconnection.js'); sql.queryAsync = util.promisify(sql.query); async function createNewId() { const newId = createId(50); const result = await sql.queryAsync('SELECT id FROM users WHERE id = ?', [newId]); return !result.length ? newId : createNewId(); }
This returns the new ID, or it calls itself again.
Usage is either with .then()
:
createNewId().then(newId => { console.log('found unused ID', newId); // do something with it }).catch(err => { console.log('oops', err); });
or inside an async
function with await
:
async function main() { try { const newId = await createNewId(); console.log('found unused ID', newId); // do something with it } catch (err) { console.log('oops', err); } }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0