fetch function return Promise <pending> [duplicate] - javascript

This question already has answers here:
Why does .json() return a promise?
(6 answers)
Closed 11 months ago.
So my code here return a Promise and since I'm using then syntax I don't know why that happens :-??
fetch('someurltoAJsonFile.json')
.then(function(response) {
console.log(response.json());});

response.json() in node-fetch library also returns a promise, instead try
fetch('someurltoAJsonFile.json')
.then(response => response.json())
.then(data => {
console.log(data)
});
you can look up more details about it here
EDIT:
It seems that the returned response wasn't in the valid json, so for the sake of completeness here is a code for text
fetch('someurltoAJsonFile.json')
.then(response => response.text())
.then(data => {
console.log(data)
});

The function given as then parameter will be executed asynchronously (sometime in the future when your server returns a response), but then itself return Promise immediately (in synchronous way) by its definition
If you want to code looks less nested (more as synchronous code) you can use await but you must opaque whole code with async function
async function load()
{
let response = await fetch('someurltoAJsonFile.json');
let data = await response.json();
console.log(data);
}

Debating whether or not this qualifies as an answer, but I ran into a similar situation today that led me to this question even though my problem ended up being environment related.
If you are seeing promise pending and your code is correct and you spend way too much time trying to figure out why the console.log isn't showing, double check that you have "Info" turned on in chrome's dev tools. I only had warnings turned on so I wasn't seeing my console.log.

This code works and show a good way to make a fetch and get the promise without the pending problem.
Run this code in your server if you have cors problem download this extension in google chrome "Allow CORS: Access-Control-Allow-Origin"
async function invoices()
{
let response = await fetch('https://blockchain.info/latestblock?utm_medium=referral&utm_campaign=ZEEF&utm_source=https%3A%2F%2Fjson-datasets.zeef.com%2Fjdorfman');
let data = await response.json();
console.log(data);
return data;
}
invoices().then(data => {
console.log(data);
});

Related

Javascript fetch POST call doesn't wait for resolve [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I am working on a Python dashboard with FastAPI and Javascript. I have created a POST call returning an URL in FastAPI, which I am trying to fetch with Javascript and pass to the player. The output of this POST call is JSON. I am trying to assign the value of a certain key to the laURL variable. The problem is that even though I am using await and async function, Javascript is not really waiting for resolving the response and the second function is executed before the completion of the laURL assignment.
async function fetchLicense(playbackURL) {
try {
let response = await fetch(apiURL, {
method: "POST"
});
if (response.ok) {
let result = await response.json();
let laURL = JSON.parse(result).la_url;
return await laURL;
} else {
console.log("POST Error: ", response);
}
} catch (error){
console.log("POST Error: ", error);
}
}
And then I am using the returned value in another function:
function fetchSource(playbackURL) {
let laURL = fetchLicense(playbackURL);
const source = {
dash: playbackURL,
drm: {
widevine: {
LA_URL: laURL
},
immediateLicenseRequest: true
}
};
return source;
I have checked and tried a couple of different solutions, but nothing seems to be working.
This should be really something straightforward, but unfortunately, the solution isn't so obvious to me.
Javascript async/await is just syntactic sugar for using Promises. fetchLicense hence returns a promise. You can use Promise.then(/* callback */) to specify what should happen when data is resolved.
If you're unfamiliar with this, the following link might help you understand how it works exactly: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Should I use response.send() in 'finally' block when writing Google Cloud Functions?

Im' trying to understand using promises with Google Cloud Functions a bit better. I just learned about the 'finally' method on promises, which is called after all promises in the chain are fully resolved or rejected. In a http function is it good practice to put response.send() inside of the finally method?
The below code uses request-promise-native for the http request. In the first .then() I call parseSchedule, which uses the cheerio web scraping api to loop through some data and on a website, and add it to the scheduledGames array (synchronously, I think).
I return from that and the then log that data to the console in writeDB, but one thing I noticed is that I see response.send() log 'execution finished' before I see the data from scheduleGames in the log. Is that correct?
Should I be using the 'finally' block like this?
Thanks,
const options = {
uri: 'https://www.cbssports.com/nba/schedule/' + urlDate,
Connection: 'keep-alive',
transform: function (body) {
return cheerio.load(body);
}
};
return request(options)
.then(parseSchedule)
.then(writeSchedule)
.catch((err) => console.log("there was an error: " + err))
.finally(res.send("execution finished"));
function parseSchedule($){
const scheduledGames = [];
$('tbody').children('tr').each((i, element) => {
const gameTime = $(element).children('td').eq(2).find('a').text()
const scheduledGame = { gameTime: gameTime};
scheduledGames.push(scheduledGame);
});
return scheduledGames;
}
function writeDB(scheduledGames){
console.log(scheduledGames);
}
}
It typically makes more sense to send a success response at the time in the promise chain when everything is successful, or send an error response in a catch handler. If you do these two things, it doesn't make sense to use finally at all, since success and error are the only two cases you really need to handle. Unless you have some special case, stick to just success and error.

Data part of Response is a long script instead of desired json object

I am building a web app using laravel and vuejs. I have made a axios get request to get a list of users .
I am getting a Promise object, and from what i have read. Reason for getting a promise object is because it's an async request.
I have tried .then() to get data part of the response. But i am getting a huge script instead of desired data.
axios......then(function(response){
console.log(response.data);
})
Initially what i did was
var res = axios.get('/allUsers');
console.log(res)
That time i came to know about promise object and read about.
When i checked network in dev tools, status code is 200 and i can see list of users. So i guess my request is successfully completed.
What should be done to get the list of the users. That list i will be using to update my UI.
Depending on what you're getting back for data there are a few ways to handle this. You may need to convert the data after the you get receive the response.
axios.get('some_url')
.then(res => res.json())
.then(data => {
// do something with the data
}).catch(err) {
conosole.error(err);
}
if you're seeing the data come through properly in the response and you're getting what you need without doing that then just do
axios.get('some url').then(res => {
// do something in here with the data here
})
also make sure you're getting back json if that's what you're looking for. check your response to see if its html or json because they can be handled a bit differently
as an "Edit" you could also handle this with async await so you dont end up in callback hell
async function fetchData() {
try {
const res = await axios.get('some url');
// next step might not be necessary
const data = await res.json();
// do something with the data
console.log(data); // if converting it was necessary
console.log(res); // if not converting
} catch (err) {
console.error(err);
}
}

Why does the following code throw a Promise in case of a non-OK HTTP code? [duplicate]

When requesting from a server with JavaScript fetch API, you have to do something like
fetch(API)
.then(response => response.json())
.catch(err => console.log(err))
Here, response.json() is resolving its promise.
The thing is that if you want to catch 404's errors, you have to resolve the response promise and then reject the fetch promise, because you'll only end in catch if there's been a network error. So the fetch call becomes something like
fetch(API)
.then(response => response.ok ? response.json() : response.json().then(err => Promise.reject(err)))
.catch(err => console.log(err))
This is something much harder to read and reason about. So my question is: why is this needed? What's the point of having a promise as a response value? Are there any better ways to handle this?
If your question is "why does response.json() return a promise?" then #Bergi provides the clue in comments: "it waits for the body to load".
If your question is "why isn't response.json an attribute?", then that would have required fetch to delay returning its response until the body had loaded, which might be OK for some, but not everyone.
This polyfill should get you what you want:
var fetchOk = api => fetch(api)
.then(res => res.ok ? res : res.json().then(err => Promise.reject(err)));
then you can do:
fetchOk(API)
.then(response => response.json())
.catch(err => console.log(err));
The reverse cannot be polyfilled.
Because somtimes we need a precise control for the loading process (from recieving the first piece of data to recieving the last one).
In actual world, json may not be a good example cause it's reletively samll. But imaging a situation where a large picture is loaded gruadually (from mosaic to clear). In that case, it is too late to inform the program when the data recieving has done completely.
Since fetch() is a relatively low level api, otherwise you could use axios or so on.

Why is the response object from JavaScript fetch API a promise?

When requesting from a server with JavaScript fetch API, you have to do something like
fetch(API)
.then(response => response.json())
.catch(err => console.log(err))
Here, response.json() is resolving its promise.
The thing is that if you want to catch 404's errors, you have to resolve the response promise and then reject the fetch promise, because you'll only end in catch if there's been a network error. So the fetch call becomes something like
fetch(API)
.then(response => response.ok ? response.json() : response.json().then(err => Promise.reject(err)))
.catch(err => console.log(err))
This is something much harder to read and reason about. So my question is: why is this needed? What's the point of having a promise as a response value? Are there any better ways to handle this?
If your question is "why does response.json() return a promise?" then #Bergi provides the clue in comments: "it waits for the body to load".
If your question is "why isn't response.json an attribute?", then that would have required fetch to delay returning its response until the body had loaded, which might be OK for some, but not everyone.
This polyfill should get you what you want:
var fetchOk = api => fetch(api)
.then(res => res.ok ? res : res.json().then(err => Promise.reject(err)));
then you can do:
fetchOk(API)
.then(response => response.json())
.catch(err => console.log(err));
The reverse cannot be polyfilled.
Because somtimes we need a precise control for the loading process (from recieving the first piece of data to recieving the last one).
In actual world, json may not be a good example cause it's reletively samll. But imaging a situation where a large picture is loaded gruadually (from mosaic to clear). In that case, it is too late to inform the program when the data recieving has done completely.
Since fetch() is a relatively low level api, otherwise you could use axios or so on.

Categories

Resources