so this is my code for the class and what i am trying to do with it
const getExternalDbInfo = require('./helperJS/get-external-db-info')
class ExternalDb {
constructor(extdb_user, extdb_password, extdb_privilege, extdb_ip, extdb_port, extdb_sid) {
this.extdb_user = extdb_user,
this.extdb_password = extdb_password,
this.extdb_privilege = extdb_privilege,
this.extdb_ip = extdb_ip,
this.extdb_port = extdb_port,
this.extdb_sid = extdb_sid
}
async getDbData(){
let data=await getExternalDbInfo(this.extdb_user, this.extdb_password, this.extdb_privilege, this.extdb_ip,
this.extdb_port, this.extdb_sid);
return this;
}
async getTablespace(){
console.log( getDbData().tablespace_data)
return getDbData().tablespace_data
}
}
const newDb= new ExternalDb("***");
(async function () {
let x =await newDb.getDbData().getTablespace()
console.log(x)
})();
so i am trying to chain to the class methods (getDbData().getTablespace()) so that i don't have to call the external db more than once. but i get following error: (node:14468) UnhandledPromiseRejectionWarning: TypeError: newDb.getDbData(...).getTablespace is not a function. Is this even possible or is it something i am not understanding because i am a noob in async programming. i have tried returning {this, data} for the getDbData() method, but it didn't work
CodePudding user response:
You need to have two await calls. await
will wait for the result of an expression, in this case, newDb.getDbData().getTablespace()
. However, getDbData()
returns a Promise
, and it's trying to find a method called getTablespace
on a Promise
, which doesn't exist.
You can either seperate this into two lines:
let x = await newDb.getDbData();
let y = await x.getTablespace();
or you can nest your await
s:
let x = await (await newDb.getDbData()).getTablespace();
CodePudding user response:
Not sure if "nesting" is the right term here, it sounds like you are trying to call the one method from the other. The correct way to do that is
class ExternalDb {
…
async getDbData(){
const data = await getExternalDbInfo(this.extdb_user, this.extdb_password, this.extdb_privilege, this.extdb_ip, this.extdb_port, this.extdb_sid);
return data;
// ^^^^
}
async getTablespace(){
const data = await this.getDbData();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
console.log(data);
return data.tablespace_data;
}
}
You would then not chain anything, but simply call
const x = await newDb.getTablespace();
console.log(x);