Reputation: 111
I'm working on a project in Node.js that uses user certificates. I need to generate them synchronously, in a blocking manner, but the library I use (pem) has only asynchronous functions (callbacks). I tried multiple ways to tackle the problem, but none of my tries have been successful. My code looks like this:
function KeyObject(CN, serverKey, days = 365) { // key object
if (typeof CN !== 'string' ||
typeof days !== 'number' ||
typeof serverKey !== 'object') {
throw TypeError;
}
this.CN = CN;
this.days = days;
const _this = this;
async function generatePrivate() {
var p = new Promise((resolve, reject) => {
pem.createPrivateKey((err, obj) => {
if (err) reject(err);
_this.private = obj.key;
resolve();
});
});
await p;
}
async function generateCert(serviceKey) {
if (typeof serviceKey !== 'object') {
throw TypeError;
}
var p = new Promise((resolve, reject) => {
pem.createCertificate({
commonName: _this.CN,
days: _this.days,
serviceKey: serviceKey.private
}, (err, obj) => {
if (err) reject(err);
_this.cert = obj.certificate;
resolve();
});
});
await p;
}
// init the keys
generatePrivate();
generateCert(serverKey);
}
This code goes straight through and doesn't wait for the functions to complete. What should I do? Thanks in advance.
Upvotes: 1
Views: 695
Reputation: 191058
You should just return the Promise
from each of those functions - no need to await
or make them async
. You also can't have an async
constructor, perhaps adding an async factory would work.
Upvotes: 1