Contents from API not being fully displayed - javascript

The code is being fetched but it is not being fully displayed, as in some parts are missing
https://github.com/KushRohra/GFG_Codes/blob/master/School/Leap%20year.cpp
You can see the code here and the one being displayed below.
However full code is being displayed in the console. dont know whats the problem
async function call() {
let url = "https://api.github.com/repos/KushRohra/GFG_Codes/contents/School/Leap year.cpp";
let response = await fetch(url);
console.log(data);
s = atob(data.content);
document.getElementById("code").innerHTML = s.replace(/\n/g, '<br>').replace(/\s/g, ' ');
}
call();
<div id="code"></div>

Heres how your code should look like:
async function call() {
let url = "https://api.github.com/repos/KushRohra/GFG_Codes/contents/School/Leap year.cpp";
let response = await fetch(url);
let data = await response.json();
console.log(data);
let s = window.atob(data.content);
document.getElementById("code").innerHTML = s.replace(/\n/g, '<br>').replace(/\s/g, ' ');
}
call();
You didn't declare data variable.
you didn't asked for a response to fetch body(response data) as a JSON() nor TEXT()
for atob function you better explicitly say window.atob() instead of atob()

Related

How to print javascript return value without clicking a button?

I want to print the followers in my webpage, it shows up in the console, but not the html document.
the code:
async function getFollowers(user) {
const response = await fetch(`https://scratchdb.lefty.one/v3/user/info/${user}`);
let responseJson = await response.json();
const count = document.getElementById.innerHTML("123");
count = responseJson.statistics.followers;
return count;}
function pfollows(user) {
const element = document.getElementById.innerHTML("123");
const USER = user;
getFollowers(USER).then(count => {
element.textContent = `${USER} has ${count} followers right now.`;
});
}
document.getElementById.innerHTML("123") seems wrong.
You should be passing an id as a string to document.getElementById like document.getElementById("someIdHere"). innerHTML is not a function and shouldn't have parentheses or an argument after it.
count looks like it should be extracted from responseJson and returned.
pfollows looks like it might be responsible for updating the actual DOM.
Redefining user as USER is somewhat redundant.
async function getFollowers(user) {
const response = await fetch(`https://scratchdb.lefty.one/v3/user/info/${user}`);
let responseJson = await response.json();
const count = responseJson.statistics.followers;
return count;
}
function pfollows(user) {
const element = document.getElementById("123").innerHTML;
getFollowers(user).then(count => {
element.textContent = `${user} has ${count} followers right now.`;
});
}
When pfollows is called, then the element with id="123" should have its content set to the desired string. If pfollows() is not called, then nothing will happen.
There's a few more possible touchups to clean up:
responseJson can probably be a const
You can inline return count without saving it to a variable return responseJson.statistics.followers
but trying to keep the changes minimal as needed to fix the problems.

How to save results of a promise to a variable? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I need to fetch some JSON data from an API and assign the result to a variable. I can see the array of data in the console, but [abc] is always set as a Pending promise.
I've tried to assign [abc] instead of logging [data] or simply returning [data] but it's not working.
Ideally, I would also want to stop the execution of the following code until I get the required data but with the code I have, the text gets logged before the data
async function fetchData()
{
let response = await fetch('API');
let data = await response.json();
data = JSON.stringify(data);
data = JSON.parse(data);
return data;
}
let abc = await fetchData()
.then(data => console.log(data));
console.log('This should not be logged if 'abc' does not have the data i need')
(data => console.log(data)) ..>> here the data is the array I need but I have no idea on how to assign on a variable.
I've looked for many solutions on the internet but I couldn't find anything that could help.
EDIT 1:
If I assign:
let abc = await fetchData()
without the then statement it throws me this error:
Uncaught SyntaxError: await is only valid in async function
If I then remove the await keyword it returns Promise without having it resolved.
In order for await keyword to work, it must sit inside a async function. So you need to wrap your code in a async function first, let's say a main function, then call it. Example:
async function fetchData() {...}
async function main() {
let abc = await fetchData();
console.log(abc);
}
main();
it should be like this
async function fetchData(){
let response = await fetch('API');
let data = await response.json();
data = JSON.stringify(data);
data = JSON.parse(data);
return data;
}
let abc = await fetchData(); // here the data will be return.
console.log(abc); // you are using async await then no need of .then().

Why are those quotations there and how can I remove them?

When I run the following code:
const root = document.querySelector('#root3');
async function fetchData(userId) {
const response = await fetch(`https://randomuser.me/api/?results=10`);
const data = await response.json();
console.log(data);
console.log(data.results);
data.results.map(item => {
root.append(`<li><img src=${item.picture.thumbnail}></li>`);
});
}
fetchData();
The result is this:
Why are those quotations there? and how can I get rid of them?
OK. You cannot use append in JavaScript.
One solution, which is working is the following:
root.innerHTML += `<li><img src=${item.picture.thumbnail}></li>`;

Unable to receive proper data from the promise function

I am trying to scrap wikipedia page to fetch list of airlines by first scrapping first page and then going to each individual page of airline to get the website url. I have divided the code in two functions. One to scrap main page and get a new url, and second function to scrap another page from the created url to get the website name from that page. I have used request-promise module for getting the html and then cheerio to parse the data.
export async function getAirlinesWebsites(req,res) {
let response = await request(options_mainpage);
console.log(`Data`);
let $ = cheerio.load(response);
console.log('Response got');
$('tr').each((i,e)=>{
let children = '';
console.log('inside function ', i);
if($(e).children('td').children('a').attr('class') !== 'new') {
children = $(e).children('td').children('a').attr('href');
let wiki_url = 'https://en.wikipedia.org' + children;
console.log(`wiki_url = ${wiki_url}`);
let airline_url = getAirlineUrl(wiki_url);
console.log(`airline_url = ${airline_url}`);
}
})
And then the getAirlineUrl() function will parse another page based on the provided url.
async function getAirlineUrl(url){
const wiki_child_options = {
url : url,
headers : headers
}
let child_response = await request(wiki_child_options);
let $ = cheerio.load(child_response);
let answer = $('.infobox.vcard').children('tbody').children('tr').children('td').children('span.url').text();
return answer;
})
However when I console log the answer variable in the parent function, I get a [object Promise] value instead of a String. How do I resolve this issue?
Async function return promise.In case of that,you need to use then to get resolved response or use await.
This should work if other part of your code is ok.
export async function getAirlinesWebsites(req, res) {
let response = await request(options_mainpage);
console.log(`Data`);
let $ = cheerio.load(response);
console.log("Response got");
$("tr").each(async (i, e) => {
let children = "";
console.log("inside function ", i);
if ($(e).children("td").children("a").attr("class") !== "new") {
children = $(e).children("td").children("a").attr("href");
let wiki_url = "https://en.wikipedia.org" + children;
console.log(`wiki_url = ${wiki_url}`);
let airline_url = await getAirlineUrl(wiki_url);
console.log(`airline_url = ${airline_url}`);
}
});
}
Since your getAirlineUrl function returns a promise, you need to await that promise. You can't have await nested inside of the .each callback because the callback is not an async function, and if it was it wouldn't work still. The best fix is the avoid using .each and just use a loop.
export async function getAirlinesWebsites(req,res) {
let response = await request(options_mainpage);
console.log(`Data`);
let $ = cheerio.load(response);
console.log('Response got');
for (const [i, e] of Array.from($('tr')).entries()) {
let children = '';
console.log('inside function ', i);
if($(e).children('td').children('a').attr('class') !== 'new') {
children = $(e).children('td').children('a').attr('href');
let wiki_url = 'https://en.wikipedia.org' + children;
console.log(`wiki_url = ${wiki_url}`);
let airline_url = await getAirlineUrl(wiki_url);
console.log(`airline_url = ${airline_url}`);
}
}
}

Getting Text From Fetch Response Object

I'm using fetch to make API calls and everything works but in this particular instance I'm running into an issue because the API simply returns a string -- not an object.
Typically, the API returns an object and I can parse the JSON object and get what I want but in this case, I'm having trouble finding the text I'm getting from the API in the response object.
Here's what the response object looks like.
I thought I'd find the text inside the body but I can't seem to find it. Where do I look?
Using the fetch JavaScript API you can try:
response.text().then(function (text) {
// do something with the text response
});
Also take a look at the docs on fetch > response > body interface methods
ES6 Syntax:
fetch("URL")
.then(response => response.text())
.then((response) => {
console.log(response)
})
.catch(err => console.log(err))
You can do this in two different ways:
The first option is to use the response.text() method, but be aware that, at Dec/2019, its global usage is only 36.71%:
async function fetchTest() {
let response = await fetch('https://httpbin.org/encoding/utf8');
let responseText = await response.text();
document.getElementById('result').innerHTML = responseText;
}
(async() => {
await fetchTest();
})();
<div id="result"></div>
The second option is to use the response.body property instead, which requires a little more work but has 73.94% of global usage:
async function fetchTest() {
let response = await fetch('https://httpbin.org/encoding/utf8');
let responseText = await getTextFromStream(response.body);
document.getElementById('result').innerHTML = responseText;
}
async function getTextFromStream(readableStream) {
let reader = readableStream.getReader();
let utf8Decoder = new TextDecoder();
let nextChunk;
let resultStr = '';
while (!(nextChunk = await reader.read()).done) {
let partialData = nextChunk.value;
resultStr += utf8Decoder.decode(partialData);
}
return resultStr;
}
(async() => {
await fetchTest();
})();
<div id="result"></div>

Categories

Resources