JavaScript, Promise {<pending>} - javascript

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 ?

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"));

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

Related

JavaScript, async await is returning a promise instead of the result

I have the below function. Why am I getting Promise { <state>: "pending" } when calling GetProfile("username")? What should I do?
const GetProfile = async (username) => {
await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => {
console.log(resp.json());
});
};
resp.json() returns a Promise and that's what you are console logging. It should resolve before getting the actual data. Since you are in an async function, you could do as below. Notice there is no need to have this then block you have.
const GetProfile = async (username) => {
const res = await fetch(`${host}/api/v1/getprofile/${username}`);
const data = await res.json();
return data;
});
};
That's normal async function behavior in javascript, they return promises.
In React, you can keep the value in a state.
const [profile,setProfile]=useState(null)
useEffect(()=> {
const GetProfile = async (username) => {
const profile = await fetch(`${host}/api/v1/getprofile/${username}`).then(resp => resp.json());
setProfile(profile)}
GetProfile(username);
},[username])
By default async function always returns promise. What you need to do is to execute it with await and you can extract the result, or chain it with then and move on.
I made an example with await:
const GetProfile = async (username) => {
await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => {
console.log(resp.json());
return resp.json()
});
};
const result = await GetProfile()
console.log(result);
NOTE:
You need to return resp.json() back from one of thens to see the result.
Because you're using .then after your async call, and resp.json() also returns a Promise which isn't being returned by your .then() call.
What happens in your case is:
const response = await fetch(`${host}/api/v1/getprofile/${username}`)
return response.json();
And because the json() function is a Promise itself (which isn't await'ed), the read of the json() call is the 'Pending' Promise that you're getting.
So to solve this, try either:
await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => resp.json())
or
const response = await fetch(`${host}/api/v1/getprofile/${username}`)
return await response.json();

How to await on a promise that is returned in an array without destructuring first?

If I have something like,
const apiCall = async (url) => {
try {
const { data } = await axios.get(url);
return [url, data];
} catch ({ response: { data } }) {
console.log('Error', data);
}
}
Say I want to call and access the data from the promise. I'd have to do something like,
const [, call] = await validate('/api/root');
const data = await call;
Is there a way to do this in a one liner, without having to access the call, something like,
await (await validate('/api/root'))?
This is an equivalent one-liner:
const data = await (await validate('/api/root'))[1]
You can put an awaited function inside an argument. So something like
const result = await apiCall(
await validate(),
url
)
Then you could handle the validation inside apiCall.
Or you could just add the validate function as a callback inside apiCall if it's dependent on the result of apiCall.

Why I get pending from this function

async function test() {
const res = await fetch('https://www.easy-mock.com/mock/5c6d317e8d040716434d0a5b/reading/category/homeSmallCategory');
console.log(res) // data
return res;
}
console.log(test()) // PromiseĀ {<pending>}
setTimeout(() => {
console.log(test()) // PromiseĀ {<pending>}
})
Please parse it at the console.
How do I deal with this problem.I want the data processing in the test function .But it always return PromiseĀ {<pending>}.
And then I think that I can deal with it like this.
if (res instanceof Promise) {
res.then(data => res = data);
}
I put it at the end of the test.But it still not working.I console the Object.prototype.toString.call(res).And then I get [object Array].I realized that inside the function. The res is an array not matter what.But at the outside the res is not alike that. I know this is something about event loop.Thanks for your help.
async function test() {
const res = await fetch('https://www.easy-mock.com/mock/5c6d317e8d040716434d0a5b/reading/category/homeSmallCategory');
console.log(res) // data
return res;
}
console.log(test()) // Promise {<pending>}
That's simply because test is an async method and async method always return a Promise. So you either chain a .then or await test()
test().then(res => console.log(res))
or
const res = await test();
console.log(res)
Try this approach.
async function test() {
const res = await fetch('https://www.easy-mock.com/mock/5c6d317e8d040716434d0a5b/reading/category/homeSmallCategory');
return res;
}
test().then(ok => {console.log(ok)}, not_ok => {console.log(not_ok)});

How can i use promise returned data in another function later on

async function getOrderdata(orderId) {
//await the response of the fetch call
let response = await fetch('http://localhost:3245/api/Orders/' + orderId);
//proceed once the first promise is resolved.
let data = await response.json();
//proceed only when the second promise is resolved
return data;
}
I have the shown code and i want to use getOrderdata function in another js file?
Put the function in a module.exports object and use an async-await function in the importing file.
// file exporting the function - exp.js
module.exports = {
getOrderdata : async function(orderId){
//await the response of the fetch call
let response = await fetch('http://localhost:3245/api/Orders/' + orderId);
//proceed once the first promise is resolved.
let data = await response.json();
//proceed only when the second promise is resolved
return data;
}
// file importing the async function - imp.js
const { getOrderdata } = require("./exp.js")
;(async () =>{
let msg = await getOrderdata()
console.log(msg)
})();

How to translate Promise code to async await

I have some simple Promise in js:
let link = "https://jsonplaceholder.typicode.com/posts/1";
fetch(link)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
... and I want to translate it to 'async await' like here:
const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1';
const fetchUsers = async () => {
const response = await fetch(API_ENDPOINT);
const data = await response.json();
};
... but I don't know how involve it in 'async await' correctly. This involving gives error:
fetchUsers()
.then(response => response.json())
.then (data => console.log(data))
.catch(error => console.error(`ERROR ${error}`));
Can you help me fix this error?
const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1';
const fetchUsers = async () => {
const response = await fetch(API_ENDPOINT);
const data = await response.json();
console.log(data);
};
Your code is working prefectly Just call fetchUsers() and It will print data through this line console.log(data);
You can't use await keyword outside the async type function
Read this -
An async function can contain an await expression that pauses the
execution of the async function and waits for the passed Promise's
resolution, and then resumes the async function's execution and
returns the resolved value.
Remember, the await keyword is only valid inside async functions. If
you use it outside of an async function's body, you will get a
SyntaxError.
Two problems here;
You don't return anything from your async function
You apply response.json() twice.
Just corect the code as;
const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1',
fetchUsers = async () => { var response = await fetch(API_ENDPOINT);
return await response.json();
};
fetchUsers().then (data => console.log(data))
.catch(error => console.error(`ERROR ${error}`));
Async functions must be functions. So, you need to create a function to do that.
MDN says:
The async function declaration defines an asynchronous function, which returns an AsyncFunction object.
Read more about that on MDN
So:
Create a function using the async keyword
Perform your fetch call inside the function using the await keyword
Perform any other operations inside your function using the await keyword around any promise related operations (if you want)
An example below:
async function doFetch(link) {
let result = await fetch(link); // this will wait the result to be fetched
console.log(result); // this will only log the result of the fetch promise after it is resolved
let json = await result.json();
console.log(json);
}
const link = 'https://jsonplaceholder.typicode.com/posts/1';
doFetch(link);
Also, remember that when you use the await keyword, your asynchronous code will actually run synchronously, so, two sequential calls to any promises will run synchronously, like so:
async function foo() {
let bar = await fetch('https://www.google.com');
// the line below will run just _*AFTER*_ the above line is completely resolved
let baz = await fetch('https://www.facebook.com');
}

Categories