0

I am new to node.js programming . I am confused how the async and await works

const async = require('async');

createUser: async (user, myid) => {
let dotill = false;
let userid = null;

const getreturn = async.whilst(
  function testCondition() { return dotill === false;},
  async function increaseCounter(callback) {
    let sr = "AB" + Math.floor(Math.random() * 99999999999) + 10000000000;
    userid = sr.substr(0, 9);
    await knex.raw('select * from userprofile where user_id=?', [userid]).then((res) => {
      console.log(res.rowCount);
      if (res.rowCount === 0) {
        dotill = true;
        callback;
      }else{
        callback;
      }
    });
  },
  function callback(err, n) {
    if (err) {
      return;
    }
    return {"done":true, "userid":userid}
  }
);

console.log(getreturn); 
// getreturn always undefined iam not getting and return 
}

getreturn is always undefined how i will be able to return in above code or any other way to working in promise..

Kapil
  • 61
  • 1
  • 8

1 Answers1

0

async/await is syntactic sugar for functions that chain promises. Do not confuse it with the callback-based async.js library, and don't use the latter when working with promises - they don't work together. Instead of trying to call async.whilst with more or less appropriate callbacks, just use a plain simple while loop:

// const async = require('async'); // remove this!

async createUser(user, myid) {
    let dotill = false;
    let userid = null;

    while (!dotill) {
        const sr = "AB" + Math.floor(Math.random() * 99999999999) + 10000000000;
        userid = sr.substr(0, 9);
        const res = await knex.raw('select * from userprofile where user_id=?', [userid]);
        console.log(res.rowCount);
        if (res.rowCount === 0) {
            dotill = true;
        }
    }
    return {"done":true, "userid":userid};
}

(also you can simplify this to a while (true) { …; if (…) return } loop without that dotill variable)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • hello Bergi is there any other way to get unique random number between in postgres query.. – Kapil Sep 17 '19 at 19:02
  • @Kapil What do you mean by "unique"? But anyway, in my answer I focused only on the promise part and left the rest of your code unchanged. If you want to create a new unique id, you should do that with postgres upon insertion. Use a sequence, a uuid, or [something else](https://stackoverflow.com/q/22908499/1048572). – Bergi Sep 17 '19 at 19:21
  • @ is there any thing like using sequence get random number between range of numbers as and id field – Kapil Sep 17 '19 at 21:14
  • @Kapil Not sure what you mean, but you'll probably want to [ask a new question](https://stackoverflow.com/questions/ask) with more detail about your requirements anyway - tag it [[tag:postgres]]. – Bergi Sep 17 '19 at 21:18