Why i'm geeting an empty Array? [duplicate] - javascript

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

Related

Javascript async function returns 'undefine' value [duplicate]

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.

React useEffect async method returning array [duplicate]

This question already has answers here:
Using async/await with a forEach loop
(33 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Returning array populated in loop by async function
(3 answers)
Closed 6 months ago.
I want to run async method and wait for the array.
My method preloadVideos doesn't return the array. What am I doing wrong?
When I console.log preloadedVideos in then section everythign is fine, but not returning. What should I change?
readyVideos is running only once and return [], but when the responses came and array has some values like [video1, video2, ...] then readyVideos is not returning, why?
Why my question is closed? Not even try to let people help me
I found your articles but it is not the same context? Why you don't let people grow?
useEffect(() => {
const preloadVideos = async (videos) => {
const preloadedVideos = [];
await videos.forEach((url) => {
axios({
url: url.url,
method: 'GET',
responseType: 'blob',
}).then((response) => {
const downloadedVideo = window.URL.createObjectURL(new Blob([response.data]));
preloadedVideos.push({ url: downloadedVideo });
});
})
return preloadedVideos;
};
if (url && isNotSingleVideo) {
const readyVideos = preloadVideos(url);
if (readyVideos.length === url.length) {
console.log('I AMA READDYY', readyVideos, url);
setVideosToWatch(readyVideos);
}
}
}
}

return variables from arrow function [JS] [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed last year.
I have this function getData which will read in a list of IDs from a JSON file. the list of IDs is stored to the idsList variable which i need to use inside another function. How do i return the value from this function
function getData(){
fetch("JSONitemIDsList.json")
.then(response => response.json())
.then(data => {
let idsList = data.ids
//return idsList
})
}
function myFunc(idsList) {
//do something with idsList
}
You can approach this in many ways. For example:
// with async / await
async function getData() {
try {
const rawData = await fetch("JSONitemIDsList.json")
const data = await rawData.json()
return data
} catch (err) {
// handle error here
console.log(err)
}
}
async function myFunc() {
const idsList = await getData()
//do something with idsList
}
or
// define first
function myFunc(idsList) {
//do something with idsList
}
function getData(){
fetch("JSONitemIDsList.json")
.then(response => response.json())
.then(data => {
// function call
myFunc(data.ids)
})
}
You can try this:
const reqResponse = fetch("JSONitemIDsList.json")
.then(response => response.json())
// I am not sure, if your data is already in the format that you need, otherwise, you can run one more .then() to format it
}
const getIdList= async () => {
const idList = await reqResponse;
console.log(idList)
// use idList to access the information you need
}

axios in javascript function to return data [duplicate]

This question already has answers here:
Async function returning promise, instead of value
(3 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I have 2 files in javascript.
One:
main_app.js
import * as API from "./api.js";
const pin = API.getPin();
console.log(pin);
other is api.js
const baseUrl = "https://some.com/api";
export function getPin() {
try {
axios.post(baseUrl, { method: "pin" }).then((res) => console.log(res));
} catch {
console.log("Fail");
}
}
In the first file I need to save the output of the getPin() but I always get Promise - pending in the console.
In the axios call and .then method I can console.log the correct data but whatever I try I am not able to return the data.
I have also tried async and await with no avail.
export async function getPin() {
try {
const res = await axios.post(baseUrl, { method: "pin" }).then(res => res.data);
return res.data;
} catch {
console.log("Fail");
}
}
I have tried class from es6 but with the same result and then thought I am probably not using the class correctly:
export class Api {
static baseUrl = "https://some.com/api";
static response = null;
static getPin() {
const body = { method: "pin" };
axios
.post(this.baseUrl, body)
.then((res) => (this.response = res.data))
.catch((err) => console.error(err));
}
}
I ve look at many articles and I am sure I am missing something obvious but I am losing my mind :-(
Any help would be appreciated
EDIT: Not really a duplicate with suggested question.I have re-did the class and it looks like this
export default class API {
static baseUrl = "https://some.com/api";
static response = null;
static pin = null;
static getPin() {
axios
.post(this.baseUrl, { method: "pin" })
.then((res) => (this.pin = res.data.pin));
return this.pin;
}
}
but this will STILL not working as I need.Help please
When using the async/await pattern with axios, .then is not needed. The await axios.post pauses the execution of code until the promise is resolved and returns the data from the API call, and thus allows for res.data to contain the response from the API. See below for a modified version of one of your examples:
export async function getPin() {
try {
// instead of this line:
// const res = await axios.post(baseUrl, { method: "pin" }).then(res => res.data);
// try the following, notice the .then() removed
const res = await axios.post(baseUrl, { method: "pin" });
// res contains the response from the API call, no need to use .then.
// you may want to console.log(res.data) out here instead to see what you get back first.
return res.data;
} catch(e) {
console.log("error: ", e);
}
}
In your main_app.js, you need to modify your code because API.getPin() is an asynchronous API call, that's why you're getting a promise.
import * as API from "./api.js";
let pinGlobal;
async function callAPIandSetPin() {
// must be awaited because API.getPin() is asynchronous.
const pin = await API.getPin();
console.log(pin);
// if you needed a global pin for whatever reason, you can modify it from here.
pinGlobal = pin;
}
callAPIandSetPin();

Consuming an Api and returning a value inside of a then [duplicate]

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

Categories

Resources