How to merge asynchronous function's callback result - javascript

Here is the code to get some information about server.
cpu.usage()
.then(info => {
console.log(info);
});
cpu.free()
.then(info => {
console.log(info)
});
mem.info()
.then(info => {
console.log(info)
});
I want to get every result in a function.
get_resource () {
...
console.log(cpu_usage, cpu_free, mem_info);
};
How can I design it?
Thank you.

You can try to use async/await to do that:
var get_resource = async function () {
var cpu_usage = await cpu.usage();
var cpu_free = await cpu.free();
var mem_info = await mem.info();
console.log(cpu_usage, cpu_free, mem_info);
};
Or
Promise.all([cpu.usage(), cpu.free(), mem.info()]).then(function (info) {
console.log('cpu_usage:', info[0]);
console.log('cpu_free:', info[1]);
console.log('mem_info:', info[2]);
})

You can use Promise.all() as following:
let cpuUsage = cpu.usage()
let cpuFree = cpu.free()
let memInfo = mem.info()
Promise.all([cpuUsage, cpuFree, memInfo]).then((values) => {
console.log(values);
});
If you can use ES6, then you can use array destructuring while getting results:
Promise.all([cpuUsage, cpuFree, memInfo]).then(([cpuUsageResult, cpuFreeResult, memInfoResult]) => {
console.log(cpuUsageResult);
console.log(cpuFreeResult);
console.log(memInfoResult);
});

Callback Hell
This is the old scenario where you would have to call things inside one another
cpu.usage()
.then(cpu_usage => {
cpu.free()
.then(cpu_free => {
mem.info()
.then(mem_info => {
console.log(cpu_usage, cpu_free, mem_info);
});
});
});
Async Await
in this scenario you make a function that is asynchronous.
async function get_resource () {
const cpu_usage = await cpu.usage();
const cpu_free = await cpu.free();
const mem_info = await mem.info();
console.log(cpu_usage, cpu_free, mem_info);
};
The value assigned to each const in the async function is the same value that you get as an argument in the callback of the then.

Related

axios.get always returning a Promise<Pending> [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 11 months ago.
I found different solutions here, but none worked for me. I have this simple code:
const Element = () => {
async function getEndData() {
const data = (await getEnd());
return data;
}
}
const getEnd = async () => {
return await axios.get('http://localhost:8080/end').then(res => res.data);
}
And it always return a Promise "pending" with inside a [[PromiseResult]] with the value i need, when i call getEndData().
I tried also to call directly getEnd() removing the then(), returning only the data, but nothing. If i print res.data in console.log, it will return the right value i need.
this should work:
const Element = () => {
async function getEndData() {
const data = await getEnd();
return data;
}
}
const getEnd = async () => {
const response = await axios.get('http://localhost:8080/end');
return response;
}
I'm not sure you are doing it the right way. You can try this:
const Element = () => {
return async function getEndData() {
const data = await getEnd();
return data;
}
}
const getEnd = () => {
return new Promise((resolve, reject) => {
axios.get('http://localhost:8080/end')
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err);
})
})
}
Also, What is the use of element function if you are not returning anything.
your getEndData() in returning a promise . add await or then where ever you are receiving the getEndData() response .
// const Element = () => {
async function getEndData() {
const data = (await getEnd());
return data;
}
// }
const getEnd = async () => {
return await axios.get('http://localhost:8080/end').then(res => res);
}
async function callEndData(){
let x = await getEndData()
console.log(x)
}
callEndData()
since it is returning promise and you are not using await or then it is showing promise pending
why do you need Element() ?
In case you need to call ELement function and also wants the data part of response you can try like this .
const Element = async() => {
async function getEndData() {
return await getEnd();
}
let fromEndData = await getEndData()
return fromEndData
}
const getEnd = async () => {
return axios.get('http://localhost:8080/end').then(res => {
return res.data
});
}
async function callEndData(){
let x = await Element()
console.log(x)
}
callEndData()
in console.log(x) i am getting the value being passed .

How can I return the response of the Axios Post in React?

I have a little problem.
I have a post function in ReactJS (totally working). I wanna have the response of it outside this function, right where I called it. How can I do that?
async function confereInicial(idAluno,idDisciplina){
return await Axios.post("http://localhost:3001/api/check",{
idAluno: idAluno,
idDisciplina: idDisciplina}).then((response)=> {
});
}
//please ignore the way I call and read my function. it's confusing but I just wanna console.log the data outside my function. ignore the map etc
return (
<div>
{
dados.state.nodesPadrao.map(p => {
confereInicial(1,p.id).then(data => console.log(data)); //how should I do that?
app.post("/api/check",(req,res) => {
const idAluno = req.body.idAluno;
const idDisciplina = req.body.idDisciplina;
const sqlSelect = "SELECT * FROM `disciplinas_feitas` WHERE id_aluno = ? AND id_disciplina = ?;"
db.query(sqlSelect,[idAluno,idDisciplina],(err,result) => {
res.send(result);
});
});
may someone please help me?
this should work for you and you can put it into a variable, you don't need to put it into a map function when you are not returning a valid JSX element from it.
const dataArray = [];
async function confereInicial(idAluno, idDisciplina) {
return axios.post("http://localhost:3001/api/check", {
idAluno: idAluno,
idDisciplina: idDisciplina
});
}
const getData = () => {
dados.state.nodesPadrao.forEach(async (p) => {
const i = await confereInicial(1, p.id);
console.log("ITEM", i);
dataArray.push(i);
});
};
useEffect(() => {
getData(); // can be called onClick or anywhere you want (make sure don't call on each re-render)
}, []);
console.log(dataArray);
I think you want
function confereInicial(idAluno,idDisciplina) {
return Axios.post("http://localhost:3001/api/check",{
idAluno: idAluno,
idDisciplina: idDisciplina
});
}
This will return a Promise, so confereInicial(1, p.id).then(response => console.log(response.data)) should work.

How to make async/wait inside of for loop?

I'm using async await inside of for loop as below.
for (let i = 0; i < result.length; i += 1) {
try{
const client = await axios.get(
`${process.env.user}/client/${result[i].id}`
);
} catch(error){
console.log(error)
}
if (client.data.success === true) {
result[i].Name = rider.data.client.Name;
result[i].PhoneNumber = rider.data.client.Number;
}
}
But I want to make this using 'new Promise' and 'promiss.all' to make it asynclously.
But I don'k know how to make this correctly doing error handle well.
Could you recommend some advice for this? Thank you for reading it.
This can be a basic solution, i think
let playList = []
for (let i = 0; i < result.length; i += 1) {
playList.push(axios.get(
`${process.env.user}/client/${result[i].id}`
).then(res => {
if (res.data.success === true) {
result[i].Name = rider.data.client.Name;
result[i].PhoneNumber = rider.data.client.Number;
}
}).catch(ex => console.log(ex)));
}
await Promise.all(playList)
This can also be done by using a foreach loop.
The for/foreach loop can be simplified by using a map function.
Js map function is equivalent of c# select linq function.
The fat arrow in js map function is not bound to return a value unlike c# select inner function which must return a value.
await Promise.all(result.map(async r => {
let client;
try {
client = await axios.get(`${process.env.user}/client/${r.id}`);
} catch (error) {
console.log(error)
}
if (client.data.success === true) {
r.Name = rider.data.client.Name;
r.PhoneNumber = rider.data.client.Number;
}
}));
Try this
var promises = result.map(r => axios.get(`${process.env.user}/client/${r.id}`);
Promise.all(promises).then(function(values) {
console.log('All promises done');
});
The idea is that if you are awaiting something, that is promise, you can await it, or call it to get promise
Example:
function Foo()
{
return new Promise(...); // Promise of int for example
}
you can do
var p = Foo(); //you will get promise
Or
var v = await Foo(); // you will get int value when promise resolved
This is how you do it with async/await + Promise.all:
const myResult = await Promise.all(result.map(({ id }) => {
return axios.get(`${process.env.user}/client/${id}`);
}));
// deal with the result of those requests
const parsed = myResult.map(data => /* your code here */);
Here is an example using Array.map to call your function along with Promise.all. I wrapped the axios request in a function so if one of your request fails, it wont stop every other requests. If you don't mind stopping when you got an issue, look at others answers to your question.
function fakeRequest() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
data: {
success: true,
client: {
Name: 'Todd',
Number: 5,
},
},
});
}, 300);
});
}
(async() => {
const result = [{}, {}, {}];
await Promise.all(result.map(async(x, xi) => {
try {
const client = await fakeRequest();
if (client.data.success === true) {
result[xi].Name = client.data.client.Name;
result[xi].PhoneNumber = client.data.client.Number;
}
} catch (err) {
console.log(err)
}
}));
console.log(result);
})();

Returning promises in javascript

I need some help returning a promise. I don't get why I am not getting the players value
The code
const playerSelectName = document.getElementById('sel1');
const playerSelectPosition = document.getElementById('sel2');
const playerSelectAge = document.getElementById('sel3');
const searchButton = document.getElementById('search-btn');
async function getPlayers() {
const response = await fetch('https://football-players-b31f2.firebaseio.com/players.json?print=pretty');
const playersObject = await response.json();
return playersObject;
}
searchButton.addEventListener('click', async () => {
const players = await getPlayers();
let [ name, position, age ] = [ playerSelectName.value, playerSelectPosition.value, playerSelectAge.value ];
yersObject.filter((playerAge) => {});
});
I cant get to access the code inside my listener function of the value players
the problem was in destructuring check the below snippet. I hope this will solve the issue . Also please update what you are trying to achieve in filter so i can add on the solution.
I didnt understood what are you trying to do in destructure part and after that filter
async function getPlayers() {
const response = await fetch('https://football-players-b31f2.firebaseio.com/players.json?print=pretty');
const playersObject = await response.json();
return playersObject;
}
const searchButton = document.getElementById('search-btn');
searchButton.addEventListener('click', async () => {
const players = await getPlayers();
players.forEach(player => {
const {name, nationality, position} = player
console.log(name, nationality, position)
})
});
<button id='search-btn'>
Load Results
</button>
Here's a simple example accessing the players to help get you started.
async function getPlayers() {
const response = await fetch('https://football-players-b31f2.firebaseio.com/players.json?print=pretty');
return response.json();
}
(async () => {
const players = await getPlayers();
console.log(players)
})();

I get Promise { <pending> } as returned value and also calling in async scope gives me undefined immediately

Im trying to return a value from a Promise in async-await form and use it in another function in another file, but I do have problem because my Promise doesnt return any value.
When im trying to console.log('website') it returns me undefined immediately (it's like the value is not being fetched at all from API services). I dont know what im doing wrong, I really love to learn about Promises and Async-Await but each time im trying to work with them im getting more confused.
const dns = require('dns')
const iplocation = require("iplocation").default;
const emojiFlags = require('emoji-flags');
const getServerIPAddress = async (server) => {
return new Promise((resolve, reject) => {
dns.lookup(server, (err, address) => {
if (err) throw reject(err);
resolve(address);
});
});
};
const getServerLocation = async (server) => {
const ip = await getServerIPAddress(server)
iplocation(ip).then((res) => {
const country = emojiFlags.countryCode(res.countryCode)
const result = `Location: ${country.emoji} ${country.name}`
return result
})
.catch(err => {
return `Location: Unknown`
});
}
(async function() {
console.log(await getServerLocation('www.google.com'))
})()
module.exports = {
getServerLocation
}
It is really important for me to get result from this function first, then use its value in another function. I wish you could give me tips on how to do tasks asynchronously.
You're clearly using async so it's not apparent why you're using then as well. If you use then then you must return the promise as well in order to preserve the promise chain:
const getServerLocation = async (server) => {
const ip = await getServerIPAddress(server)
return iplocation(ip).then((res) => {
const country = emojiFlags.countryCode(res.countryCode)
const result = `Location: ${country.emoji} ${country.name}`
return result
})
.catch(err => {
return `Location: Unknown`
});
}
Otherwise just async this:
const getServerLocation = async (server) => {
const ip = await getServerIPAddress(server)
let res = await iplocation(ip);
const country = emojiFlags.countryCode(res.countryCode)
const result = `Location: ${country.emoji} ${country.name}`
return result
}
const getServerLocation = async (server) => {
const ip = await getServerIPAddress(server)
//you need to return
return iplocation(ip).then((res) => {
const country = emojiFlags.countryCode(res.countryCode)
const result = `Location: ${country.emoji} ${country.name}`
return result
})
.catch(err => {
return `Location: Unknown`
});
}

Categories