async function getChampionID(randomChampionID) {
let response = await fetch('http://ddragon.leagueoflegends.com/cdn/11.10.1/data/en_US/champion.json');
let body = await response.json();
var championData = Object.keys(body.data)
var randomChampionKey = Math.floor(Math.random() * (154 - 0 + 1) + 0)
return randomChampionID = championData[randomChampionKey]
}
async function getChampionName(randomChampionName) {
let result = await getChampionID();
let response = await fetch(`http://ddragon.leagueoflegends.com/cdn/11.10.1/data/en_US/champion/${result}.json`)
let body = await response.json();
return randomChampionName = body.data[result].name
}
var randomChampion = document.getElementById('random-champion')
var bgimg = document.getElementById('background-image')
var championSquare = document.getElementById('square')
randomChampion.addEventListener("click", async () =>
{
let championID = await getChampionID()
let championName = await getChampionName()
bgimg.style.backgroundImage = `url('http://ddragon.leagueoflegends.com/cdn/img/champion/splash/${championID}_0.jpg')`
championSquare.src=`http://ddragon.leagueoflegends.com/cdn/11.11.1/img/champion/${championID}.png`
console.log(championID)
console.log(championName)
})
The getChampionName() function takes a random value from getChampionID, so whenever I call both of them through a button event listener, the getChampionID() generates a random ID (#1), the getChampionName() once again takes another value from getChampionID(), result in a different ID (#2), but I need the getChampionName() to take the #1 ID
Firstly, the functions are not being passed a parameter and therefore do not need anything within the parentheses when being defined.
Secondly, within the event listener, I would simply call a function called getChampion that gets a random ID, then gets the details, and returns both the champion detail and the ID for further use as an object.
My code would look like this.
async function getChampionID() {
let response = await fetch('http://ddragon.leagueoflegends.com/cdn/11.10.1/data/en_US/champion.json');
let body = await response.json();
var championData = Object.keys(body.data)
var randomChampionKey = Math.floor(Math.random() * (154 - 0 + 1) + 0)
return championData[randomChampionKey]
}
async function getChampion() {
let result = await getChampionID();
let response = await fetch(`http://ddragon.leagueoflegends.com/cdn/11.10.1/data/en_US/champion/${result}.json`)
let body = await response.json();
return { name: body.data[result].name, id: result }
}
var randomChampion = document.getElementById('random-champion')
var bgimg = document.getElementById('background-image')
var championSquare = document.getElementById('square')
randomChampion.addEventListener("click", async () =>
{
let champion = await getChampion()
bgimg.style.backgroundImage = `url('http://ddragon.leagueoflegends.com/cdn/img/champion/splash/${champion.id}_0.jpg')`
championSquare.src=`http://ddragon.leagueoflegends.com/cdn/11.11.1/img/champion/${champion.id}.png`
console.log(champion.id)
console.log(champion.name)
})
Related
async function generateNextNrOf() {
const companyOf = await Company.find().limit(1).sort({ $natural: -1 });
const now = new Date();
const month = now.getUTCMonth() + 1;
const year = now.getUTCFullYear();
let poprzedniNr = companyOf[0].nrOf;
let checkingTab = [];
checkingTab = poprzedniNr.split('/');
if (month === parseFloat(checkingTab[0])) {
let newNumber = `${month}/${year}/Of/${parseFloat(checkingTab[3]) + 1}`;
console.log(newNumber);
return newNumber;
} else {
let newNumber = `${month}/${year}/Of/1`;
console.log(newNumber);
return newNumber;
}
}
I checking from MongoDB last record, I am looking for a variable named "nrOf" (4/2022/Of/1).
I try generate next number like 4/2022/Of/2 and so on and so forth.
If I try run generateNextNrOf(); I only get the Promise, but i need this result "pass" to variable, like const exampleVariable = '4/2022/Of/2';
I know async/await always return a Promise, but probably is the solution for my case.
async function generateNextNrOf() {
const companyOf = await Company.find().limit(1).sort({ $natural: -1
});
const now = new Date();
const month = now.getUTCMonth() + 1;
const year = now.getUTCFullYear();
let poprzedniNr = companyOf[0].nrOf;
let checkingTab = [];
checkingTab = poprzedniNr.split('/');
if (month === parseFloat(checkingTab[0])) {
let newNumber =
`${month}/${year}/Of/${parseFloat(checkingTab[3]) + 1}`;
console.log(newNumber);
return newNumber;
} else {
let newNumber = `${month}/${year}/Of/1`;
console.log(newNumber);
return newNumber;
}
}
I think you are calling this function from non-async function.Like this--
function main(){
const exampleVriable = await generateNextNrOf();
console.log(exampleVriable);
}
So the problem is main is not an async function ,thus you cannot use await in main.
To solve this problem you must use async keyword before main.Here is the solution.
async function main(){
const exampleVriable = await generateNextNrOf();
console.log(exampleVriable);
}
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();
}, []);
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();
This is the code to fetch all the results from the website.
const puppeteer = require('puppeteer');
let students = [];
let rollPrefix = '387EA';
let regPrefix = 'EA87S18';
let currRoll = 80;
let currReg = 80;
let i = 0;
(async () => {
const browser = await puppeteer.launch({
headless: false, // Show the window for debugging
slowMo: 150 // slow down by 50ms
});
const page = await browser.newPage();
let rolltemp = rollPrefix + pad(currRoll,3);
let regTemp = regPrefix + pad(currReg,3);
while(i < 4){
await page.goto('http://orissaresults.nic.in/CHSE');
await page.type('#txtRollNo', rolltemp);
await page.type('#txtRegNo', regTemp);
const element = await page.$("#divCaptch");
const text = await (await element.getProperty('textContent')).jsonValue();
await page.type('#txt_UserCaptcha', text);
await page.click('#btnSubmit');
page.on('dialog', async (dialog) => {
await dialog.dismiss().catch(() => {
console.log(dialog.message());
return new Result(TestStatus.FAIL, dialog.message());
})})
try{
await page.waitForNavigation()
await page.waitForSelector('table');
const RollNO = await page.evaluate(() => {
return document.querySelectorAll('table')[2].rows[0].cells[1].innerText.trim();
});
const Name = await page.evaluate(() => {
return document.querySelectorAll('table')[2].rows[2].cells[1].innerText.trim();
});
const RegNo = await page.evaluate(() => {
return document.querySelectorAll('table')[2].rows[1].cells[1].innerText.trim();
});
const Total = await page.evaluate(() => {
return document.querySelectorAll('table')[3].rows[8].cells[0].innerText.trim();
});
let student = new Student(RollNO,Name,RegNo,Total)
students.push(student)
}catch{
currReg++;
continue;
}
currRoll++;
i++;
}
await browser.close()
// let json = JSON.stringify(students);
// storeData(json,'test.json')
})();
// function delay(time) {
// return new Promise(function(resolve) {
// setTimeout(resolve, time)
// });
// }
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
class Student {
constructor(roll,name,reg,total){
this.roll = roll;
this.name = name;
this.reg = reg;
this.total = total;
}
}
const fs = require('fs')
const storeData = (data, path) => {
try {
fs.writeFileSync(path, data)
} catch (err) {
console.error(err)
}
}
Here the variable value of currReg stays the same pls help
The code tries each roll no and reg no combinations but there are some reg no that doesnt match with roll no so in the code the roll no should stay the same but the reg no should increase by one..
Not really sure what should happen with each combination, but here's an implementation which inputs all combinations. Below a short explanation:
const puppeteer = require('puppeteer');
let students = [];
(async () => {
const browser = await puppeteer.launch({
headless: false, // Show the window for debugging
slowMo: 150 // slow down by 50ms
});
const page = await browser.newPage();
let i = 0;
let j = 0;
const rollPrefix = '387EA';
const regPrefix = 'EA87S18';
let currRoll = 80;
let currReg = 80;
while(i < 4){
while(j < 4) {
let rolltemp = rollPrefix + pad(currRoll,3);
let regTemp = regPrefix + pad(currReg,3);
console.log("rolltemp = ", rolltemp, " regtemp = ", regTemp);
await page.goto('http://orissaresults.nic.in/CHSE');
await page.type('#txtRollNo', rolltemp);
await page.type('#txtRegNo', regTemp);
const element = await page.$("#divCaptch");
const text = await (await element.getProperty('textContent')).jsonValue();
await page.type('#txt_UserCaptcha', text);
await page.click('#btnSubmit');
page.on('dialog', async (dialog) => {
await dialog.dismiss().catch(() => {
console.log(dialog.message());
return new Result(TestStatus.FAIL, dialog.message());
})})
try{
await page.waitForNavigation()
await page.waitForSelector('table');
const RollNO = await page.evaluate(() => {
return document.querySelectorAll('table')[2].rows[0].cells[1].innerText.trim();
});
const Name = await page.evaluate(() => {
return document.querySelectorAll('table')[2].rows[2].cells[1].innerText.trim();
});
const RegNo = await page.evaluate(() => {
return document.querySelectorAll('table')[2].rows[1].cells[1].innerText.trim();
});
const Total = await page.evaluate(() => {
return document.querySelectorAll('table')[3].rows[8].cells[0].innerText.trim();
});
let student = new Student(RollNO,Name,RegNo,Total)
students.push(student)
} catch {
continue;
}
currReg++;
j++;
}
currReg = 80;
j = 0;
currRoll++;
i++;
}
await browser.close()
// let json = JSON.stringify(students);
// storeData(json,'test.json')
})();
// function delay(time) {
// return new Promise(function(resolve) {
// setTimeout(resolve, time)
// });
// }
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
class Student {
constructor(roll,name,reg,total){
this.roll = roll;
this.name = name;
this.reg = reg;
this.total = total;
}
}
const fs = require('fs')
const storeData = (data, path) => {
try {
fs.writeFileSync(path, data)
} catch (err) {
console.error(err)
}
}
Explanation
so, assuming you want all combinations of pairs {currentRol, currentReg}, you'll definitely need two loops. There are gonna be 4x4=16 combinations in total (I assume, basing on i < 4 condition). First mistake which you made was assigning regTemp before while loop, effectively not changing the strings entered to the inputs, only some unused, temporary values (currentRoll, currentReg). So, first and foremost is to move rollTemp and regTemp definitions into the while loop. Now, as I said, you're gonna need two nested loops, as you need to generate all possible combinations (for each currentRol, all currentRegs). One more thing to remember is that you'll have to reset currentReg with each outer loop iteration, as you want to test each reg for given roll.
Note about variables' scopes
This is a great example why variables scopes are critical when programming. Not only it increases readability and comprehensibility of the given code - it prevents other functions/scopes from using symbols which do not really belong to them. Please notice where the variables definitions are within my snippet. Probably it's not perfect, but why would you pollute global namespace as in your example?
I have an async generator that yields a the updated value when next() is invoked.
I want to invoke next() on every clicks but it seems thatthe generaor is not invoked and it always return the first value
How can i handle this ?
const baseApi = `https://hacker-news.firebaseio.com/v0`;
const topStories = [
19571054,
19570735,
19570986,
19571139,
19571399,
19569865,
19561411,
19571027,
19560994
];
const fetchAsyncA = async url => await (await fetch(url)).json();
const sliceBy = (list, start, end) => list.slice(start, end);
async function* hackerNewsStreamer(ids, slice) {
let start = 0;
while (start <= ids.length) {
let urls = sliceBy(ids, start, start + slice).map(
id => `${baseApi}/item/${id}.json?print=pretty`
);
yield await Promise.all(urls.map(fetchAsyncA));
start += slice;
}
}
document.querySelector("button").addEventListener("click", async () => {
const articlesStream = hackerNewsStreamer(topStories, 5);
const { value: articles } = await articlesStream.next();
console.log(articles);
//console.log(await articlesStream.next());
//console.log(await articlesStream.next());
//console.log(await articlesStream.next());
});
https://codepen.io/daniele-bolla/pen/MRKMBX