Strount
Strount

Reputation: 5

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');
}

Upvotes: 0

Views: 1204

Answers (2)

jfriend00
jfriend00

Reputation: 707696

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);
 });

Upvotes: 0

Arun Devarajan
Arun Devarajan

Reputation: 59

An async function returns a promise by default. Please call await createCode() in another async function or use createCode().then()

Upvotes: 1

Related Questions