Reputation: 38
async function db(path){
const res = await fetch('data.json');
const data = await res.json();
return data[path];
}
console.log(db("name"));
how can i fix the Promise {pending} I am trying to get Global Access to my database json file from anywhere in my code is this right way or there is a better way ?
Upvotes: 1
Views: 341
Reputation: 1599
The problem is that you have an async function that returns a promise, but you call it in a not async way. What you should simply do is add an await before your call:
async function db(path){
const res = await fetch('data.json');
const data = await res.json();
return data[path];
}
console.log(await db("name"));
Upvotes: 2
Reputation: 6418
The return of the function simply returns another promise. So you can modify your function like this-
async function db(){
const res = await fetch('data.json');
const data = await res.json();
return data;
}
db().then(data => console.log(data['name']);
Note: You should not return anything from a async function. You should do what you want inside the funciton
Upvotes: 0