promise is still pending in then block - how to resolve? [duplicate] - javascript

This question already has answers here:
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Closed 4 years ago.
I have code something like -
fetch(`${URL}${PATH}`)
.then(res => {
const d = res.json();
console.log("data is: ", d);
return d;
})
It logs data is: Promise { <pending> }.
What to do to see results and utilize in next code statement?
Other questions and answers suggests to use then block to resolve, but I'm still seeing it unresolved.

res.json() is asynchronous. You will need to use an additional .then to get the result.
fetch(`${URL}${PATH}`)
.then(res => res.json())
.then(d => {
console.log('data is: ', d);
return d;
});

Well If you are getting this type of value Promise { <pending> }. Always remember to resolve it.
So your query would resolve to
fetch(`${URL}${PATH}`)
.then(res => res.json())
.then(console.log)
.catch(console.error)
For better understanding you can leverage the use of async/await feature. The above code would reduce to-
try{
const res = await fetch(`${URL}${PATH}`)
const dataAsJson = await res.json()
console.log(data)
}
catch(ex) {
console.error(ex)
}

Related

Can't use data returned from Fetch API [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 trying to get data from this API using fetch, and I know a promise pending is returned, but it isn't resolving itself so I can't use the data. I don't know what I am doing wrong.
function api () {
return fetch('https://api.punkapi.com/v2/beers').then(respo => { respo.json() } ).then(data => {
const beersData = data;
return beersData;
}).catch(error => {
console.error(error)
}) ;
}
api();
console.log(beersData)
First of all, you need to remove curly bracket in first then.
respo => respo.json() is equivalent to respo => { return respo.json() }.
And second, you need to handle promise when you call api function since api() also returns Promise.
function api () {
return fetch('https://api.punkapi.com/v2/beers')
.then(respo => respo.json())
.then(data => {
const beersData = data;
return beersData;
}).catch(error => {
console.error(error)
}) ;
}
api()
.then(res => {
console.log(res);
})

javascript/vue.js async/await and .then (promise) not waiting until completion of fetch in login function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I build a login function and check the credentials on my backend-server. I have to wait for the response of the server. I have used an official guide to es7-async-await.js, but it does not work. I have tried everything that async/await and promises give, but it does not work at all. I read all the posts regarding this issue. What am I doing wrong?
My function:
async getCredentials(pUser, pCipher) {
var url = new URL(serviceURL);
var params = {
user: pUser,
p: pCipher
}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
// await response of fetch call
let response = await fetch(url, {
method: 'get',
headers: { }
});
// only proceed once promise is resolved
let data = await response.json();
// only proceed once second promise is resolved
return data;
},
my function call:
this.getCredentials(this.input.username, cipher)
.then(data => this.checkResponse = data.items)
.catch(reason => console.log(reason.message))
console.log("data: ->>>> " ,this.checkResponse);
the result:
data is always empty because the function does not wait
can you put the console.log in the .then?. Is printing something?. If you do a console.log when the data is not received will not print anything.
this.getCredentials(this.input.username, cipher)
.then(data =>
{
this.checkResponse = data.items
console.log("data: ->>>> " ,this.checkResponse);
})
.catch(reason => console.log(reason.message))

How can i pass to the next promise the previous promise's result? [duplicate]

This question already has answers here:
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 3 years ago.
I have a chain of promises in my backend and i need to access the result of the first promise in the second one
mongo.connect()
.then((client) => {
return circolari.infiniteScroll(client, currCirc)
})
.then(({ data, client }) => {
mongo.close(client)
res.send(data)
})
.catch(error => res.sendStatus(error.message))
I need to access client to close the connection in the second promise.
Right now to achieve that I resolve in circolari.infiniteScroll(client, currCirc) an object like this:
resolve({
data: data,
client: client
})
With this workaround it works, but I think there's a better way to do it, thank you.
You can make it a little bit shorter:
mongo.connect()
.then(client => circolari.infiniteScroll(client, currCirc)))
.then(({ data, client }) => {
mongo.close(client);
res.send(data);
})
Or using await and async:
async function returnResponse(res) {
let client;
try {
client = await mongo.connect();
const data = await circolari.infiniteScroll(client, currCirc);
res.send(data);
} catch (err){
res.sendStatus(err.message)
} finally {
await mongo.close(client); // close connection in every case
}
}
foo();

Get both return values of a promise chain [duplicate]

This question already has answers here:
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 3 years ago.
I have a promise chain inside of a function and I would like to console.log the values returned from 2 functions inside of the chain. How would I do this? With my current code I get the value from si.cpuTemperature() then undefined but I would like to get the value from si.cpu() then si.cpuTemperature().
const si = require('systeminformation');
function getCPUInfo() {
return new Promise((resolve) => {
resolve();
console.log("Gathering CPU information...");
return si.cpu()
// .then(data => cpuInfo = data) - no need for this, the promise will resolve with "data"
.catch(err => console.log(err)); // note, doing this will mean on error, this function will return a RESOLVED (not rejected) value of `undefined`
})
.then(() => {
return si.cpuTemperature().catch(err => console.log(err));
});
}
getCPUInfo().then((data1, data2) => console.log(data1, data2));
From the docs,
systeminformation.method() returns a promise. So you don't really need to wrap it inside a promise constructor, ie new Promise()
To get the cpu and temperature, since they are not dependent on each other, you can do either use parallel promises along with an async function or just parallel promises
async function getCpuAndTemperature() {
const [cpu, temperature] = await Promise.all([
si.cpu(),
si.cpuTemperature()
])
console.log(cpu, temperature)
}
or
function getCpuAndTemperature() {
return Promise.all([
si.cpu(),
si.cpuTemperature()
])
.then(([cpu, temperature]) => {
console.log(cpu, temperature)
})
}

Node-fetch returns Promise { <pending> } instead of desired data [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am currently trying to fetch JSON from a website using the node-fetch module, and have made the following function:
var fetch = require("node-fetch");
function getJSON(URL) {
return fetch(URL)
.then(function(res) {
return res.json();
}).then(function(json) {
//console.log(json) logs desired data
return json;
});
}
console.log(getJson("http://api.somewebsite/some/destination")) //logs Promise { <pending> }
When this is printed to the console, I simply receive Promise { <pending> }
However, if I print the variable json to the command line from the last .then function, I get the desired JSON data. Is there any way to return that same data?
(I apologize in advance if this is just a misunderstanding issue on my part, as I am rather new to Javascript)
A JavaScript Promise is asynchronous. Your function is not.
When you print the return value of the function it will immediately return the Promise (which is still pending).
Example:
var fetch = require("node-fetch");
// Demonstational purpose, the function here is redundant
function getJSON(URL) {
return fetch(URL);
}
getJson("http://api.somewebsite/some/destination")
.then(function(res) {
return res.json();
}).then(function(json) {
console.log('Success: ', json);
})
.catch(function(error) {
console.log('Error: ', error);
});

Categories

Resources