Can I use variables that are inside functions outside them? - javascript

async function players_online() {
const response = await fetch("http://ip:port/dynamic.json");
const data = await response.json();
console.log(data.clients);
}
Can i use data inside other function? Exemple:
async function players() {
console.log(data.clients);
}
When i do this i recive undefined

"Yes", you can:
let data
async function players_online() {
const response = await fetch("http://ip:port/dynamic.json");
data = await response.json();
}
async function players() {
// You can't ensure data is already set!!!
console.log(data.clients);
}
However you can not ensure that data is already defined at that point. You have to ensure by your own code that players_online is called and awaited before you call players.
You can ensure this with a call order like that:
async function players_online() {
const response = await fetch("http://ip:port/dynamic.json");
const data = await response.json();
await players(data)
}
async function players(data) {
console.log(data.clients);
}

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

Export a variable from a function in Javascript

All i want is take userId variable's value to use anything.
async function getMyData(){
const token = '';
spotifyApi.setAccessToken(token);
const data = await spotifyApi.getMe();
let userId = data.body.id;
return userId;
}
const userId = getMyData();
console.log(userId)
console.log(userId) saying me this: {Promise <pending<}
With any async functions, don't forget to use await before function execution
/// ./getMyData.js
export async function getMyData(){
// ...
return userId;
}
/// ./otherFile.js
import {getMyData} from './getMyData.js'
(async function () {
const userId = await getMyData();
console.log(userId)
})()
you are using async await features in your code.
Thus the return type of your getMyData would actually be a Promise object.
More about Promises here
Now, heres how you can use your function in another file without having to use the await keyword.
import { getMyData } from '%your file path%';
getMyData().then(function(userId) {
// use the value of userId here
console.log(userId);
}

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.

JavaScript, Promise {<pending>}

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

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)
})();

Categories