我想为我的程序创建一个 ID。ID 是随机的,但我必须确保它不存在于数据库中。为此,我搜索了 ID,如果搜索结果为空,则 ID 通过,但如果搜索找到某些内容,则需要重新开始该过程。
在 PHP 中,我可以为我的代码执行此逻辑:
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;
如何在 node.js 中实现基本上异步执行的相同逻辑?
我试过这个但没有奏效:
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);