admin管理员组文章数量:1379238
I am trying to get values from my local database, but all I can get is 'Promise{<Pending>}'. Here is my code that I found on the internet. The code below should return a result object that contains table rows, but I am only getting promise.
const getFromDB = async() =>{
return await pool.query('SELECT * FROM services');
};
I am trying to get values from my local database, but all I can get is 'Promise{<Pending>}'. Here is my code that I found on the internet. The code below should return a result object that contains table rows, but I am only getting promise.
const getFromDB = async() =>{
return await pool.query('SELECT * FROM services');
};
Share
Improve this question
edited Feb 10, 2019 at 3:54
karel
5,89560 gold badges57 silver badges59 bronze badges
asked Feb 9, 2019 at 16:26
Petr MPetr M
1633 gold badges3 silver badges13 bronze badges
2
-
How dou you call
getFromDB()
? – eol Commented Feb 9, 2019 at 16:38 - Duplicate stackoverflow./questions/48626761/… ? – Hubbitus Commented Feb 9, 2019 at 22:53
1 Answer
Reset to default 6An async
function always returns a promise. The resolved value of that promise is whatever value the code in your function returns. So, to get the value out of that promise, you use either await
or .then()
;
getFromDB().then(val => {
// got value here
console.log(val);
}).catch(e => {
// error
console.log(e);
});
There is no free lunch in Javascript. A value obtained asynchronously can only be returned from a function asynchronously (via callback or promise or other similar async mechanism).
Or, if the caller itself was an async function, then you could use await
:
async function someOtherFunc() {
try {
let val = await getFromDb();
console.log(val);
} catch(e) {
// error
console.log(e);
}
}
本文标签: javascriptHow to get value from async functionStack Overflow
版权声明:本文标题:javascript - How to get value from async function? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744002609a2574135.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论