Async function printing empty var - javascript

I want to call a function and return a value from another function the problem is that the value is empty
async function Print(){
var result = await readFile();
console.log(result);
}
async function readFile() {
const FileName = ['g.png','g2.png'];
const Files = FileName.length;
texts = '';
FileName.forEach( async function(FileName) {
Tesseract.recognize(FileName,'ara',{ logger: m => console.log(m) }).then(({ data: { text } }) => {
texts += text;
console.log(texts);
})});
return texts;
}

the following implementation using for of loop should work. Check out this post for more information.
async function readFile() {
const FileName = ['g.png','g2.png'];
const Files = FileName.length;
let texts = '';
for (fName of FileName){
const { data: { text } } = await Tesseract.recognize(fName,'ara',{ logger: m => console.log(m)});
texts += text;
console.log(texts);
}
return texts;
}

Related

Trying to declare variable within useEffect:

I'm really not sure what I am doing wrong
Please help out...
Is there a better way to access a variable declared within the useEffect?
Thanks
So I have the following code - but I get the error:
[TypeError: "setDevice" is read-only]
const [device, setDevice] = useState( '' );
React.useEffect(() => {
const device_id = async () => {
var DeviceInfo = require('react-native-device-info');
var deviceId = DeviceInfo.getUniqueId();
const filePath = RNFS.DocumentDirectoryPath + deviceId + "_secret.json";
if (await RNFS.exists(filePath)){
RNFS.readFile(filePath, 'utf8')
.then((contents) => {
try{
// setDev = String(contents);
var JSONObject = JSON.parse(contents);
console.log(JSONObject['device_id']);
setDevice = JSONObject['device_id'];
}catch(err){
console.log("Error: ", err);
}
});
console.log("FILE EXISTS: " + filePath);
} else {
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var dev_id = makeid() + deviceId;
var id = '{"device_id" : "'+dev_id+'"}';
RNFS.writeFile(filePath, id, 'utf8')
.then((success) => {
console.log('FILE WRITTEN!');
navigation.dispatch(resetReachOutPreferences)
})
.catch((err) => {
console.log(err.message);
});
}
}
device_id();
}, []);
console.log("ID: " + device);
I've tried useState(null)
From the React documentation on the State hook:
What does useState return? It returns a pair of values: the current state and a function that updates it.
So in this case, setDevice is a function that can be used to update the value of device (which will be reflected on subsequent renders). Instead of assigning to it, you should call it with the new value as its argument, e.g.:
setDevice(contents);

PromiseĀ {<pending>} being returned and await key word not working [duplicate]

This question already has an answer here:
Getting Promise pending ..- ES6
(1 answer)
Closed 12 months ago.
When running the below code and dumping out the results variable it returns PromiseĀ {<pending>}, I have added the await key word to the being of the function call so const results = await getAllResults() however this returns the error of Unexpected reserved word 'await'.
Anyone have any ideas?
useEffect(() => {
async function getPageOfResults(page) {
const response = await axios.get('https://swapi.dev/api/starships/?page=' + page);
return response.data.results;
}
async function getAllResults() {
let starships = [];
let lastResultsLength = 10;
let page = 1;
while (lastResultsLength === 10) {
const newResults = await getPageOfResults(page);
page++;
lastResultsLength = newResults.length;
starships = starships.concat(newResults);
}
return starships;
}
const results = getAllResults();
}, []);
You need to add async in the useEffect like so:
useEffect(async () => {
async function getPageOfResults(page) {
const response = await axios.get('https://swapi.dev/api/starships/?page=' + page);
return response.data.results;
}
async function getAllResults() {
let starships = [];
let lastResultsLength = 10;
let page = 1;
while (lastResultsLength === 10) {
const newResults = await getPageOfResults(page);
page++;
lastResultsLength = newResults.length;
starships = starships.concat(newResults);
}
return starships;
}
const results = await getAllResults();
}, []);

Async call in javascript For Loop not working

I have a callback function inside a loop here for (var res in results) {
but it seems the loop is not waiting for the async call. When I am calling self.callTestOutputData(test_output_url) here, the loop is not waiting fpor the response but continuing for the next iteration and I am losing out the value to push into obj.requistion_number = testOutputResponse.value;
Please note : var results = response.results Here results is an array of Json objects.
Edit 1 : I tried forEach but that didn't work .
results.forEach(res => {
var obj = {}
obj.ferp = res.name;
// your code...
})
Original Code:
self.downloadDailyExcelProcurement = function (filters, excelTmpArr) {
self.disableExcelDownloadProcurement(true);
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label')[0].style.backgroundColor = "gray";
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label .demo-download-icon-24')[0].style.color = "#D8D8D8";
var payload = {};
if (typeof filters === "string") {
var fill = filters;
} else {
var fill = self.sendFilters();
if(self.app() === "fusion"){
fill += '&module=Procurement';
}else if (self.app() === "o2r"){
fill += '&module=O2r';
}
}
if(fill.includes("%3A")){
fill = fill.replace(/%3A/g, ':');
}
payload.Endpoint = 'executions/testcollection/' + fill;
//console.log(payload.Endpoint)
payload.BeforeSend = function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('guest:oracle123'));
$(".custom-loader-circle").show();
};
payload.OnSuccess = function (response) {
var results = response.results;
for (var res in results) {
var obj = {}
obj.ferp = results[res].name;
obj.po = "NA"
obj.receipt_no = "NA"
var test_output_url = results[res].reference_test_cases[0].automation_tests[0].test_outputs[0]
$.when(self.callTestOutputData(test_output_url)).done(function (testOutputResponse) {
if(testOutputResponse)
obj.requistion_number = testOutputResponse.value;
else {
obj.requistion_number = "NA";
}
self.excelTmpArr().push(obj);
});
}
else {
self.excelTmpArr().push(obj);
}
}
if (response.next) {
filters = ((response.next).split('testcollection'))[1];
if (filters[0] === "/") {
var test = filters.slice(1, filters.length);
}
self.downloadDailyExcelProcurement(test, self.excelTmpArr());
} else {
if (results.length === 0) {
$(".custom-loader-circle").hide();
self.disableExcelDownloadProcurement(false);
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label')[0].style.backgroundColor = "#4d0000";
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label .demo-download-icon-24')[0].style.color = "white";
showMessage(self.messages, "No Data to Download", '', 'info');
} else {
self.formatForExcel(self.excelTmpArr(), fill, "Procurement");
}
}
};
payload.OnError = function (data) {
showMessage(self.messages, data.status, data.statusText, 'error');
$(".custom-loader-circle").hide();
};
getData(payload);
}
Try using async and await :
async function asyncCall () {
// call here
}
for (var res in results) {
const response = await asyncCall();
}
var results = response.results;
if(result.length > 0){
results.map((data,index)=>{
//write your code here
})
}
This will help you ..
Use forEach() to iterate since it creates its own function closure:
results.forEach(res => {
var obj = {}
obj.ferp = res.name;
// your code...
})

node js async function won't stop

I am trying to break from the loop in an async function in node js, but it seems not to work. Once the script it's done, it starts executing again from the beginning. I can't use process.exit(), because then it won't save my logs.
Any idea how can I terminate this function?
Here is the code:
async function program() {
const xlsxFile = require('read-excel-file/node');
let rows = await xlsxFile('./file.xlsx', { sheet: 'sheet' });
const userRolesArray = [rows[0][1], rows[0][2]];
let roles = await getAllRoles();
let users = await getAllUsers();
let count = 0;
roleId = null;
for (userRole in userRolesArray) {
for (i in rows){
let someObject = {
test1: rows[i][0],
test1: rows[i][2],
};
if (someObject.test1 =='undefined') {
fs = require('fs')
await fs.appendFile('log_file.txt', i+")"+JSON.stringify(someObject)+"\n", function (err) {
if (err) throw err;
// console.log('Saved!');
});
} else {
//do something else;
}
}
}
count++;
if (userRole === '1') {
// loop has reached the end...Now exit
break;
}
};
program().then(() => {
return "Finished....!"
});

Node.js How to retrieve data from http.get response

I am doing some practice in node.js. In this exercise I been asked to find a country name through a GET Http Request to an endpoint passing a page integer as a parameter.
Where the important response structs are these {page, total_pages, data}.
page is the current page,
total_pages is the last page,
data is an array of 10 country object.
In getCountryName func I am able to retrieve the right answer only if the answer is on the 1st page, the 1 iteration of the loop. So, why the loop only happens once?
Aditional, I wanted to retrieve the total_pages to replace the hardcode '25' value but I do not figure it out how to return it along with the search.
Any hint you wanna give me? The whole problem is in getCountryCode func.
'use strict';
const { Console } = require('console');
const https = require('https');
function makeRequest(page){
return new Promise(resolve => {
let obj='';
https.get('https://jsonmock.hackerrank.com/api/countries?page='+page, res => {
let data ='';
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
obj=JSON.parse(data);
resolve(obj);
});
});
});
}
async function getCountryName(code) {
var res = '';
var pages = 25;
var i = 1;
while(i <= pages && res == ''){
console.log(i);
res = makeRequest(i)
.then(data => {
let f = ''
let p = data['total_pages'];
let search = data['data'].find(o => o.alpha3Code === code);
f = search != null ? search['name'] : f;
return f;
});
i++;
}
return res;
}
async function main() {
const name = await getCountryName('ARG');
console.log(`${name}\n`);
}
main();
Without modifying your code too much, this is how you do it:
'use strict';
const { Console } = require('console');
const https = require('https');
function makeRequest(page){
return new Promise(resolve => {
let obj='';
https.get('https://jsonmock.hackerrank.com/api/countries?page='+page, res => {
let data ='';
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
obj=JSON.parse(data);
resolve(obj);
});
});
});
}
async function getCountryName(code) {
const pages = 25;
var i = 1;
let f = null
while(i <= pages && f === null){
console.log(i);
const data = await makeRequest(i) // put in try/catch
const p = data['total_pages'];
const search = data['data'].find(o => o.alpha3Code === code);
f = search !== null ? search['name'] : null;
i++;
}
return res;
}
async function main() {
const name = await getCountryName('ARG');
console.log(`${name}\n`);
}
main();

Categories