Search code examples
node.jsobjectpromisereturn

object Promise on return


Whenever I'm trying to generate random keys from crypto or nanoid (new library) it just returns [object Promise]

async function createCode(length){
  if(!length){
    return nanoid;
  } else {
    return nanoid(length);
  }
}

// another one for example
async function createCode(){
  return await crypto.randomBytes(64).toString('hex');
}

Solution

  • All async function return a promise. Always.

    So, the caller of an async function has to either use await themselves (from within another async function) or use .then() to get the value out of the promise.

    It doesn't look to me like either of your functions benefit from being async. return await someFunc() when someFunc() returns a promise can be done with just return someFunc() just the same. The await is not necessary at all.

    FYI, crypto.randomBytes() uses a callback if you want the asynchronous version. If you don't pass it a callback, then it's just a plain synchronous function. Unless you've done something to make a promisified version of that library, it doesn't return a promise.

    So, you can just use this:

    // another one for example
    function createCode(){
      return crypto.randomBytes(64).toString('hex');
    }
    

    Which you can just call as a regular function:

    let randomVal = createCode();
    console.log(randomVal);
    

    If you want the asynchronous version and want to use it with promises, then you'd have to promisify it:

    // another one for example
    function createCode(){
      return new Promise((resolve, reject) => {
           crypto.randomBytes(64, function(err, val) {
               if (err) return reject(err);
               resolve(val.toString('hex'));
           });
      });
    
    }
    

    Then, you can call it:

     createCode().then(val => {
         console.log(val);
     }).catch(err => {
         console.log(err);
     });