The event handler for websocket connection (wss.on
) is called that calls an async function sendInitialState()
. There I call an async function (getMetadata()
) that returns a Promise in which I do some async stuff. I resolve the promise, resolve(res)
is called, but the program still blocks on await, that is console.log(metadata)
is never called.
wss.on('connection', (ws) => {
sendInitialState();
});
const sendInitialState = async (ws) => {
console.log('Sending initial state!');
const metadata = await getMetadata();
console.log('metadata:', metadata);
};
const getMetadata = async () => {
return new Promise((resolve, reject) => {
MongoClient.connect(url, (err, db) => {
if (err) {reject(err);}
else {
db.collection("meta").findOne({type: 'a'}, (err, res) => {
if (err) reject(err);
else {
db.close();
console.log('Metadata found: ', res);
resolve(res);
}
});
}
});
});
}
What is the reason my program blocks?
(I tried adding async before outer (ws) =>
, but outcome is the same)
if (err) throw err
is wrong and should beif (err) return reject(err);
in both places you have it. For future reference,if (err) throw err
should pretty much NEVER be in your code, ever. I've never encountered a circumstance where that is correct error handling. And, then you need to put atry/catch
around yourawait
so you can catch any errors that might happen. Error handling is not to be ignored here and is probably the first thing you should look at when things are not working as expected. – jfriend00console.log('metadata:', blockchainMetadata);
. You're referring to the wrong variable in your log statement. – jfriend00catch()
. Why isthrow
in this case invalid, isn't this just a performance thing since there isn't optimization aroundthrow
? – petebreject()
is JUST an ordinary function call. Your function keeps executing the rest of the code in the block. You should use regular flow control to separate out the code you want to execute in the error path from the non-error path. Regular Javascript programming techniques. – jfriend00