0

How can i handle error on this nodejs promise function I'm new to Promise. i tried i everything but i can't handle it. I want to if generate function finish res.send okay if has a error res send error. I tried finally, catch, try catch blocks anything not worked.

my code:

exports.gameCreatePost = function (req, res) {


    function shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array
    }
    var code;
    generate(8, 10).then(function (ok) {
        console.log(ok)
        code = ok;
        var chance = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        chance = shuffleArray(chance);
        Game.create({
            username: req.body.username,
            code: code,
            gameChance: chance,
            opened: 0,
            log: [],
            total: 0,
            status: 0,
            creator: req.user.username
        }, function (err, created) {
            if (err) {
                console.log(err)
            } else {
                res.send('ok')
            }
        });
    },function(err) {
        res.send('error')
    });

}

function generate(count, retry) {
    return new Promise(function (resolve, reject) {
        var _sym = 'A';
        var str = '';
        for (var i = 0; i < count; i++) {
            str += _sym[parseInt(Math.random() * (_sym.length))];
        }
        const control =  Game.findOne({
            code: str
        })
        if (retry <= 0) {
            reject('Code Not Generated')
        } else if (control) {
            console.log('inside')
            generate(count, retry - 1)
        } else {
            resolve(str);
        }
    }).catch(function (err) {
        console.log(err);
    });
}
  • You've misplaced a period with a comma in your gameCreatePost function's catch chain. – Tyler Miller Mar 09 '20 at 22:39
  • In `generate()` are you trying to promisify `Game.findOne()`? There's no other reason you would need a Promise, but promisification doesn't quite work like that. – Roamer-1888 Mar 09 '20 at 23:07
  • In `gameCreatePost()`, you will also benefit from also [promisifying](https://stackoverflow.com/a/22519785/3478010) `Game.create()` – Roamer-1888 Mar 09 '20 at 23:13

0 Answers0