This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 28 days ago.
I am new to Javascript. I am trying to retrieve data from a MQTT broker through an async JavaScript function, querydevice. Here I am successfully getting a response from functions.logger.log(`Query msg retrived from MQTT ${msg}`) as expected.
const querydevice = async () => {
let msg;
try {
await client.subscribe("test/result");
client.on('message', function(topic, message) {
msg = message.toString();
var tp = topic.toString();
client.end();
functions.logger.log(
`Query msg retrived from MQTT ${msg}`
);
});
return {
state: msg,
}
} catch (e) {
process.exit();
}
};
I am calling the function querydevice in another function called app.onQuery as below. But I am not getting a correct response in functions.logger.log(`Device state:${dt.state}`). It shows undefined in place of the dt.state variable in the logs.
app.onQuery(async (body) => {
const dt = await querydevice();
functions.logger.log(`Device state:${dt.state}`);
return {
requestId: body.requestId,
payload: {
devices: {
"OOB-Group-7": {
on: false,
online: true
}
}
}
}
});
Can some one guide me where I am doing wrong?
I tried removing await, used .then instead in app.onQuery function. Also I tried .toString() for the dt variable.
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 months ago.
Main function
export async function postData(TVMID) {
const data = await FetchingData(TVMID)
// regex the year
const rex = /^[0-9]{4}/g;
let country;
let network;
let geners = await CheckGenderIfExist(data.genres).then(genx => genx)
more code....
}
Check if data exist function
export async function CheckGenderIfExist(genders) {
let listOfGenders = [];
if (Array.isArray(genders)) {
genders.forEach(gen => {
axios.get(`${process.env.NEXT_PUBLIC_API_URL}/api/genders?filters[$and][0][Name][$eq]=${gen}`)
.then((response) => {
if (response.data.data.length == 0) {
AddTVGenders(gen)
} else {
listOfGenders.push(response.data.data[0].id)
}
});
})
} else {
axios.get(`${process.env.NEXT_PUBLIC_API_URL}/api/genders?filters[$and][0][Name][$eq]=${genders}`)
.then((response) => {
listOfGenders.push(response.data.data[0].id)
});
}
return listOfGstenders;
}
Add missing data function
export async function AddTVGenders(gen) {
await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/api/genders`, {
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`,
},
"data": {
Name: gen,
}
})
CheckGenderIfExist(gen)
}
Im' using strapi v4.5 with nextjs v13, while tring to post data for some of the relation fields , i have to check if the data exist if not, i create it then get the id then add it to the main post function
This is what i came up with but it return empty array
This question already has answers here:
Why do I need to await an async function when it is not supposedly returning a Promise?
(3 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
This is my first time using promises and mongoose, and I'm trying to save data to global variable for later use
const getUser = async () => {
let user
try {
user = await clientModel.findOne({username: email})
consoe.log(user)
} catch (e) {
console.log(e)
}
return user
}
const filteredUser = getUser().then((value) => {
return value
}).catch((e) => console.log(e));
console.log(filteredUser)
user console log displays content:
{
_id: new ObjectId("61aa75c64e1526131d98f2a1"),
username: 'paul#beatles.uk',
chequing: null,
saving: '1000022',
__v: 0
}
but filteredUser keeps displaying Promise { <pending> }
You need to resolve promise for use data. Read about that here
It can be await or then
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a nodejs app and I am trying to pass a value called membership to a page. I initialize it and try to update its value in a function but the output doesn't change. It still outputs 0. Please I need help
app.get("/",(req,res)=>{
var membershipStrength = 0;
memberData.findAll()
.then(members =>{
// console.log(members.length);
membershipStrength = members.length;
console.log(membershipStrength);
})
.catch(err => {
console.log("Error fetching members data: ", err);
});
console.log(membershipStrength);
return res.render("index",
{
page: "Admin",
membershipStrength: membershipStrength,
// tableData : global.dataOut
}
);
});
You're calling the render function before the call to findAll completes. Thus, when your server responds to the HTTP request, it still has the original value of membershipStrength in it.
You need to put the call to render inside the then handler:
app.get("/",(req,res)=>{
var membershipStrength = 0;
return memberData.findAll()
.then(members =>{
// console.log(members.length);
membershipStrength = members.length;
console.log(membershipStrength);
return res.render("index",
{
page: "Admin",
membershipStrength: membershipStrength,
// tableData : global.dataOut
}
);
})
.catch(err => {
console.log("Error fetching members data: ", err);
});
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm consuming an API that returns a famous quote, i wanna grab that quote and consume another api to search for an image related to that quote, but when i make a function that returns the famous quote and call it, it always returns Undefined.
I've tried with promises and async and even timeouts but i haven't been able to return anything.
This is file generate.js
const unirest = require('unirest');
exports.getQuote = function() {
unirest.get("https://andruxnet-random-famous-quotes.p.rapidapi.com/?cat=movies&count=1")
.header("X-RapidAPI-Host", "andruxnet-random-famous-quotes.p.rapidapi.com")
.header("X-RapidAPI-Key", "api-key").then(async (response) => {
const {quote} = await response.body[0];
return (quote);
});
}
quote.js
const middleware = require('../middleware/generate');
router.get('/look',(req,res) => {
async function call() {
const quote = await middleware.getQuote()
setTimeout(function() {
console.log('quote has: ', quote);
}, 5000);
}
call();
res.status(200).json({
message: 'its working'
});
});
When i call generate.js the output is the quote, but when i call it form the quote.js the output is undefined
Try returning the http.get:
exports.getQuote = function () {
return unirest.get("https://andruxnet-random-famous-quotes.p.rapidapi.com/?cat=movies&count=1")
.header("X-RapidAPI-Host", "andruxnet-random-famous-quotes.p.rapidapi.com")
.header("X-RapidAPI-Key", "api-key").then(async (response) => {
const { quote } = await response.body[0];
return (quote);
});
};
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
So I have a function that uses the refresh token I have to get a new access token and I want to use this function before every call that requires an access token.
The first function refreshAccessToken() makes the request and returns the response including the body that contains the new access token. Now I thought this was enough but I was getting undefined followed by the actual data and doing some digging I found this question:
Promise returns undefined
which led me to returning the value from this function so the promise resolves fully and using it in another, returnAccessToken().
returnAccessToken() is supposed to take the resolved promise value and return the access token but it behaves unexpectedly. The console.log line works like a charm and it logs the correct value everytime but when I return the token and try to use it in the function below it, it is undefined again.
api.js
"use strict"
const request = require("request-promise-native");
refreshAccessToken: async function (credentialsObject) {
const options = {
method: "POST",
uri: <refresh token uri>,
resolveWithFullResponse: true,
json: true
};
return await request(options);
},
returnAccessToken: function (auth) {
this.refreshAccessToken(auth)
.then(function (result) {
// This logs the result correctly
console.log(result.body);
return result.body;
}, function (err) {
console.log(err);
});
},
actionRequiringAccessToken: function (auth) {
let tokens = this.returnAccessToken(auth);
// This returns undefined
console.log(tokens);
}
index.js
Also yes I realize that logging here does nothing as I don't currently return a value I just include it because this is how actionThatRequiresAccessToken() is run in my setup.
"use strict"
const api = require("api");
let auth = {
// Credentials
};
api.actionRequiringAccessToken(auth)
.then(function (data)) {
console.log(data);
}, function (err) {
console.log(err);
}
Just add return in returnAccessToken method.. you are not returning anything
returnAccessToken: function (auth) {
return this.refreshAccessToken(auth)
return result.body;
That returns the data into the .then chain. So actually your method doesnt return anything. Might add a return here:
returnAccessToken: function (auth) {
return this.refreshAccessToken(auth) /*...*0
}
I would suggest make actionRequiringAccessToken async and drop returnAccessToken
actionRequiringAccessToken: async function (auth) {
let response = await this.returnAccessToken(auth);
let tokens = response.body //parse the response... whatever returnAccessToken does
console.log(tokens);
}