I am developing an application based on nodejs and electron, that has to retrieve data from an nedb-database. I have not fully understood the concept of Promises, or I think I have understood it far enough to use it, but it always ends up in a mess of a dozen nested callbacks because of the asynchronous nature of promises.
I am aware of threads like this one and the solutions brought up there. Using callbacks or the .then().method of Promises might be fine if that code path is a "dead end" (e.g. errorhandling), but for many sequential lines, it will end up in endlessly nested code.
I am also aware one should not use return await ...()
, but I tried some ways to make an asynchronous method synchronous. The following code brought up some questions:
function getFromDatabase() {
return new Promise((resolve, reject) => {
//do something with asynchronous database api
resolve('database element');
})
}
async function getSynchronous() {
var dbElement = await getFromDatabase();
console.log("before returning: " + dbElement)
return dbElement;
}
console.log("returned: " + getSynchronous());
The code will return:
returned: [object Promise]
before returning: database element
Why is the same object (dbElement) containing the string when logging it inside the function ('before returning: ...') and containing the promise when handed back through the
return
of the functionWhy is the returned object logged to console before the one inside the function is?