How can I retrieve the data from Promise object in React? - javascript

Here is my code snippet for parsing application data:
async function parseApplication(data: Application) {
const fieldGroupValues = {};
for (const group of Object.keys(data.mappedFieldGroupValues)) {
const groupValue = data.mappedFieldGroupValues[group];
for (const fieldName of Object.keys(groupValue.mappedFieldValues)) {
const { fieldValue } = groupValue.mappedFieldValues[fieldName];
}
return fieldGroupValues;
}
But I receive data as Promise object, how can I retrieve data from Promise?

In you example you are combining both of await and .then(), I would use only one of them.
Preferably await as the following:
try {
const dict = await getDictionaryByKey(fieldValue.value.entityDefinitionCode);
const dictItem = dict.find((item) => fieldValue.value.entityId === item.code);
acc[fieldName] = dictItem ? dictItem.text : fieldValue.value.entityId;
} catch (err) {
acc[fieldName] = fieldValue.value.entityId;
}

Related

Adding specific API responses to AsyncStorage in React Native on button press

In my React Native app i'm trying to add specific API responses to AsyncStorage on button press. Here's what my API request and save to AsyncStorage looks like:
onSearch = async () => {
const results = await API.get(`/${searchText}`);
await AsyncStorage.setItem('favourites',JSON.stringify(results));
}
And here's what i'm currently doing to save specific different responses to AsyncStorage on pressing save :
const onPressSave = async () => {
//here's my current response data in variable data
var data = await AsyncStorage.getItem('favourites')
var favouriteData = await AsyncStorage.getItem('list')
if (favouriteData === null) {
await AsyncStorage.setItem('list',JSON.stringify(data))
}else {
var PreviousfavouriteData = await AsyncStorage.getItem('list')
var allData = [data, PreviousfavouriteData]
console.log('All Data >>>',allData )
}
}
This is only adding two responses to allData variable. How can i add more than two responses on pressing save button.
You can try this code, I hope it helps you.
const onPressSave = async () => {
const storageKey = ['favourites', 'list', 'others'];
let allData = [];
for (let i = 0; i < storageKey.length; i++) {
const tempData = await AsyncStorage.getItem(storageKey[i]);
const parseTempData = JSON.parse(tempData);
if (parseTempData) {
allData = [...allData, ...parseTempData];
} else {
// AsyncStorage.setItem() here
}
}
}

Storing MongoDB document inside a Node.js array and return it

I try to get specific documents from MongoDB with Node.js and insert them into array.
const getStockComments = async (req) => {
const stockname = req.params.stockName;
var comments = [];
var data = [];
const stock = await stockModel.findOne({ name: stockname });
comments = stock.comments;
comments.forEach(async (commentId) => {
const comm = await commentModel.findOne({ _id: commentId });
data.push(comm);
console.log(data); // This returns the data in loops, because its inside a loop.
});
console.log(data); // This not returns the data and i don't know why.
return data;
};
The first console.log(data) returns the same data a lot of times because its inside a loop.
But the second console.log(data) dosen't returns the data at all.
What I'm doing wrong?
Instead of using loop , you can use $in operator to simplify things .
const getStockComments = async (req) => {
const stockname = req.params.stockName;
var comments = [];
var data = [];
const stock = await stockModel.findOne({ name: stockname });
comments = stock.comments;
commentModel.find({ _id: { $in: comments } }, (err, comments) => {
data = comments;
});
console.log(data);
return data;
};

How to make promise to wait for all objects to be complete and then push to array?

The getURL() function creates an array of scraped URLs from the original URL. getSubURL() then loops through that array and scrapes all of those pages' URLs. Currently, this code outputs just fine to the console, but I don't know how to wait for my data to resolve so I can push all gathered data to a single array. Currently, when I try and return sites and then push to array, it only pushes the last value. I believe it's a promise.all(map) situation, but I don't know how to write one correctly without getting an error. Ideally, my completed scrape could be called in another function. Please take a look if you can
const cheerio = require('cheerio');
const axios = require('axios');
let URL = 'https://toscrape.com';
const getURLS = async () => {
try {
const res = await axios.get(URL);
const data = res.data;
const $ = cheerio.load(data);
const urlQueue = [];
$("a[href^='http']").each((i, elem) => {
const link = $(elem).attr('href');
if (urlQueue.indexOf(link) === -1) {
urlQueue.push(link);
}
});
return urlQueue;
} catch (err) {
console.log(`Error fetching and parsing data: `, err);
}
};
const getSubURLs = async () => {
let urls = await getURLS();
try {
//loop through each url in array
for (const url of urls) {
//fetch all html from the current url
const res = await axios.get(url);
const data = res.data;
const $ = cheerio.load(data);
//create object and push that url into that object
let sites = {};
sites.url = url;
let links = [];
//scrape all links and save in links array
$("a[href^='/']").each((i, elem) => {
const link = $(elem).attr('href');
if (links.indexOf(link) === -1) {
links.push(link);
}
//save scraped data in object
sites.links = links;
});
// returns list of {url:'url', links:[link1,link2,link3]}
console.log(sites);
}
} catch (err) {
console.log(`Error fetching and parsing data: `, err);
}
};
Don't think this is a Promise related issue at heart.
You'll need to collect your sites into an array that is initialized outside the loop. Then when getSubURLs() resolves, it will resolve to your array:
const getSubURLs = async() => {
let urls = await getURLS();
let siteList = [];
try {
for (const url of urls) {
// :
// :
// :
siteList.push(sites);
}
} catch (err) {
console.log(`Error fetching and parsing data: `, err);
}
return siteList; // array of objects
};
getSubURLs().then(console.log);

Get the variable data/result from the promise in React JS after running it through map

I want the result of activeCustomers array inside the last then but I keep getting an error saying arrow function expects a return. Not sure how I can get activeCustomers?
const CreateCustomer = (storeData) => {
let activeOrganization = null;
storeData.Org
.getOrganization()
.then(function createCustomer(organization) {
activeOrganization = organization[0];
const dataArray= storeData.attributes;
activeOrganization
.createAttributes(
attributeType[0],
getSomeData(dimensions)
)
.then(function Properties(createdAttribute) {
updateCustomerProperty(createdAttribute, attributeType[0]);
});
activeOrganization
.createAttributes(
attributeType[1],
getSomeData(dimensions)
)
.then(function Properties(createdAttribute) {
updateCustomerProperty(createdAttribute, attributeType[1]);
});
}).then(() => {
activeOrganization
.getCustomers()
.then((cusomters) => {
const activeCustomers = [];
cusomters.map((customer) => {
activeCustomers.push(customer);
});
return activeCustomers;
})
.then((activeCustomers) => {
console.log(activeCustomers);
});
});
};
//Now I want the result of activeCustomers array inside the last then but I keep getting an error saying arrow function expects a return. Not sure how I can get activeCustomers?
I want the result of activeCustomers array inside the last then but I keep getting an error saying arrow function expects a return. Not sure how I can get activeCustomers?
In your example i think you received a warning. But still how to access to activeCustomers it depends on how you want to use it there are you storing it.
If you want to store it globally then you can store it like that
let activeCustomers;
....
.then((cusomters) => {
activeCustomers = [];
cusomters.map((customer) => {
activeCustomers.push(customer);
});
return activeCustomers;
})
But i think it's better to rewrite to async/await.
const CreateCustomer = async (storeData) => {
let activeOrganization = null;
const [activeOrganization] = await storeData.Org
.getOrganization();
const activeOrgPrs = attributeType.map(x => activeOrganization
.createAttributes(
x,
getSomeData(dimensions)
)));
const attrs = await Promise.all(activeOrgPrs);
attrs.forEach((attr, i) => {
updateCustomerProperty(attr, attributeType[i]);
})
const cusomters = await activeOrganization
.getCustomers();
return cusomters;
};
And you can use it like const customers = await CreateCustomer(someData);
or like CreateCustomer(someData).then((cusomters) => { activeCustomers = cusomters; return null;(if it keeps to return errors)});

Return array inside promise is returning undefined

I'm learning NodeJS a bit to do some automation scripts, but I'm having a problem that I don't know how to solve.
Using google spreadsheet API and "promisify-node" package, I'm requesting some data from an spreadsheet, and trying to return part of the data to be used on another js file.
file: spreadsheet.js
const getProductsConfiguration = async(auth) =>
{
const sheets = google.sheets('v4');
const getValues = promisify(sheets.spreadsheets.values.get);
await getValues({
auth: auth,
spreadsheetId: utils.getSpreadsheedId(config.spreadsheet.configSpreadsheedUrl),
range: `${config.spreadsheet.configTabName}!A8:C1000`,
})
.then(function (response) {
var productsConfiguration = [];
for(var value in response.values)
{
if(response.values[value].length === 0) continue;
var productConfig = {
"productName": response.values[value][0],
"spreadsheetId": response.values[value][1],
"filterId": response.values[value][2]
};
productsConfiguration.push(productConfig);
}
console.log(productsConfiguration);
return productsConfiguration;
})
.catch(function (error){console.log(error); return false;});
};
app.js:
productsConfig = await spreadsheet.getProductsConfiguration(sheetAuth);
console.log(productsConfig);
this console.log is returning "undefined", but the console.log inside "spreadsheet.js" is returning the correct data.
What can I do to solve? thanks
You can just do const values = await getValues({...}).No need to put a then after it since the promise resolves to the values when you use await in front of a function that returns a promise.
const getProductsConfiguration = async(auth) => {
const sheets = google.sheets('v4');
const getValues = promisify(sheets.spreadsheets.values.get);
let values
try{
values = await getValues({
auth: auth,
spreadsheetId: utils.getSpreadsheedId(config.spreadsheet.configSpreadsheedUrl),
range: `${config.spreadsheet.configTabName}!A8:C1000`,
})
}catch(e){
console.log(error)
}
var productsConfiguration = [];
if(values){
for(var value in values) {
if(values[value].length === 0) continue;
var productConfig = {
"productName": values[value][0],
"spreadsheetId": values[value][1],
"filterId": values[value][2]
};
productsConfiguration.push(productConfig);
}
}
console.log(productsConfiguration);
return productsConfiguration
};
Hope this helps !

Categories

Resources