ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

mysql – 重构非阻塞nodejs do..while循环

2019-09-02 10:15:32  阅读:217  来源: 互联网

标签:mysql loops node-js nonblocking


我正在node.js写一个api.第一个Web服务端点 – / create – 创建一个带有随机6字符哈希的新数据库条目,非常类似于bit.ly哈希.

PHP中做了类似的事情之后,我编写了一个do..while循环,它生成一个随机字符串并检查我的mysql db(使用node-mysql)以确保它是免费的.我在那里也有一个计数器,所以如果需要,我可以在x次迭代后失败.

var i = 0;
var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var hash = null;
var success = false;

do {

    // generate a random hash by shuffling the alphabet, 
    // joining it and getting 6 chars
    hash = alphabet.sort(function(){ 
        return 0.5 - Math.random();
    }).join('').substr(0,6);

    console.log(i + ': checking hash ' + hash);

    // see if it exists in the db
    db.query("SELECT hash FROM trips WHERE hash = " + hash, function(err, results){

        if(results.length == 0) {
            // the hash is free to use :)
            success = true;
        } else {
            // the hash is already taken :(
            success = false;
        }

    });

    // increment the counter
    i++;

} while(success === false && i < 10);

我目前在我的db(abcdef)中只有一个哈希,但是循环达到10并且失败,因为它认为每个新哈希已经存在.

我很确定这是因为node.js的非阻塞性质.这显然是一件好事,但在我的情况下,我需要阻止循环,直到查询返回.

我很确定我可以通过做类似的事情来解决这个问题:

var q = db.query(...);

但我知道这会丢掉node.js的一个主要功能.

是否存在针对此类需求的代码模式?

解决方法:

I’m pretty sure this is because of the non-blocking nature of node.js.

是.

This is obviously A Good Thing, but in my case I need the loop to block until the query has returned.

不,你肯定不想这样做.

拥抱异步approcach.使用回拨:

function generateHash(onSuccess, one rror, retryCount) {
    // generate a random hash by shuffling the alphabet, 
    // joining it and getting 6 chars
    var hash = alphabet.sort(function(){ 
        return 0.5 - Math.random();
    }).join('').substr(0,6);

    // see if it exists in the db
    db.query(
    "SELECT hash FROM trips WHERE hash = '" + hash + "'", 
    function(err, results){
        if (results.length == 0) {
            // the hash is free to use :)
            onSuccess(hash);
        } else {
            // the hash is already taken :(
            if (retryCount > 1) {
                generateHash(onSuccess, one rror, retryCount - 1);
            } else {
                one rror();
                }
            }
        }
    });
}

generateHash(
  function(hash) { console.log('Success! New hash created: ' + hash); },
  function() { console.log('Error! retry limit reached'); },
  6
);

标签:mysql,loops,node-js,nonblocking
来源: https://codeday.me/bug/20190902/1790306.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有