How to fetch data Array in Promise [duplicate] - javascript

This question already has answers here:
Why does .json() return a promise?
(6 answers)
Closed 6 years ago.
I call API on my react JS app :
result = fetch('http://localhost:5000/cities')
result.then(function(response) {
console.log(response.json());
})
Then output log :
Promise
__proto__ : Promise
[[PromiseStatus]] : "resolved"
[[PromiseValue]] : Array[5]
0: Object
1: Object
2: Object
3: Object
4: Object
length: 5
__proto__: Array[0]
How do I fetch data on Array ?
I need get city name list

The line response.json() returns a promise that resolves to the parsed JSON.
You can simply write
result.then(function(response) {
return response.json();
}).then(function (data) {
console.log(data);
});

Related

Accessing and looping through data in Promise [duplicate]

This question already has answers here:
what is right way to do API call in react js?
(14 answers)
async/await implicitly returns promise?
(5 answers)
Closed 26 days ago.
I have a promise from Fetch that I use to get the list of countries from our API:
async fetchDataFromAPI () {
console.log('fetchDataFromAPI')
let response = await fetch(process.env.NEXT_PUBLIC_BRIDGEMAN_API_URL + '/countries',
{
method: 'GET',
headers: {
'Content-Type': 'application/ld+json',
'Accept': 'application/json'
}
})
let data = await response.json();
return data
}
I call that promise inside of a class component in componentDidMount:
componentDidMount() {
this.setState({countries: this.fetchDataFromAPI()})
}
Then when I pass it to the render function, Like this:
const {
countries
} = this.state
console.log('state countries', countries)
I get the following output in my console:
Promise { <state>: "pending" }
<state>: "fulfilled"
<value>: Array(244) [ {…}, {…}, {…}, … ]
[0…99]
[100…199]
[200…243]
length: 244
<prototype>: Array []
<prototype>: Promise.prototype { … }
All the data is there in the ''. I just dont know how to get at it?
I've tried countries.then((data) => {console.log('data', data)}) but I get the message that countries has no method .then. I've tried countries.map and that is the same error.
How can I loop through and output the data on the page?

Typescript , get a specific property of response data

Below is my response data format.
In Typescript : how to get the 1st item's "_Name" value which is inside the "ResultList" array of the response data ?
Using this.responseData$.subscribe(val => console.log(val));
I am able to see the response data in browser
ResultList: Array(1)
0: {
_CodeID: "112344",
_Name: "ABCGDJFJFJF", // Want to get this property value
_IsADV: false
}
length: 1
__proto__: Array(0)
_Acknowledge: 2
_Bild: "5256"
_CId: "641645DF-E5E5-481A-B8E7-94FE2DRFFFFF"
_MachineName: "*******"
_Message: ""
_ReservationExpires: ""
_RId: ""
_RowsAffected: 0
_Version: "1.0"
It depends on the context how you later plan to use this variable, but one option is to just extract it in the subscribe block:
this.responseData$.subscribe(val => {
const whatIsNeeded = val.ResultList[0]._Name;
// do somehting with variable whatIsNeeded
});
Other one is to pipe it to another observable.
const whatIsNeededObservable: Observable<string> = this.responseData$.pipe(map(val => val.ResultList[0]._Name));
More info about piping and mapping can be found here: https://www.learnrxjs.io/learn-rxjs/operators/transformation/map

Vue.js Can't get the data out of a get request into 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 am running a server that is serving a Vue.js app.
So if I input http://localhost:9999/ into my browser,
the browser gets 4 important files:
post.js, get.js, vue.js and the index.HTML with the vue code.
I got a dynamic ordered list to work where each list element
has a button to add an element and to remove itself as well as
a debug button which outputs some variables to the console.
Now I need to make a get request to my server to get an Array with JSON data
that will create some elements in a second ordered list.
I tried the following but nothing works:
//get("http://localhost:9999/text/1", inputData)
//get("http://localhost:9999/text/1").then(inputData)
//inputData = get("http://localhost:9999/text/1")
This is the content of get.js:
//which is correctly included in the vue.js index.HTML
//<script SRC="get.js"> </script>
function get(url, params) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.setRequestHeader('Content-type', 'application/json');
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
//resolve(req.response);
resolve(JSON.parse(req.response));
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(req.statusText);
}
};
// Handle network errors
req.onerror = function() {
reject("Network Error");
};
// Make the request
req.send(params);
});
}
After the vue.js method block I call
mounted() {
this.$nextTick(function () {
var inputData=[]
//get("http://localhost:9999/text/1", inputData)
//get("http://localhost:9999/text/1").then(inputData)
inputData = get("http://localhost:9999/text/1")
app.vueData = inputData
console.log(inputData)
console.log(JSON.stringify(inputData))
console.log(';)')
})
}
The Promise has the content but I can't transfer it to the variable.
Promise {<pending>}
__proto__: Promise
catch: ƒ catch()
constructor: ƒ Promise()
finally: ƒ finally()
then: ƒ then()
Symbol(Symbol.toStringTag): "Promise"
__proto__: Object
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(4)
0: {text: "This List"}
1: {text: "was pulled"}
2: {text: "from the"}
3: {text: "server"}
length: 4
__proto__: Array(0)
Since comments get deleted I have to get creative:
#Apal Shah
Thanks for this answer. Your code looks way better than the then() solution.
I got wind of the culprit before reading your solution by adding a lot of console.log()s
console.log('app.vueData vor app.vueData = inputData: ')
console.log(app.vueData)
app.vueData = inputData
console.log('inputData nach Zuweisung: ')
console.log(inputData)
console.log('JSON.stringify(inputData)')
console.log(JSON.stringify(inputData))
console.log(';)')
Console Output:
get block: (index):153
app.vueData vor app.vueData = inputData: (index):156
[__ob__: Observer] (index):157
length: 0
__ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__: Array
inputData nach Zuweisung: (index):161
[__ob__: Observer] (index):162
length: 0
__ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__: Array
JSON.stringify(inputData) (index):164
[] (index):165
;) (index):167
Download the Vue Devtools extension for a better development experience: vue.js:9049
https://github.com/vuejs/vue-devtools
You are running Vue in development mode. vue.js:9058
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
(4) [{…}, {…}, {…}, {…}] (index):154
0: {text: "This List"}
1: {text: "was pulled"}
2: {text: "from the"}
3: {text: "server"}
length: 4
__proto__: Array(0)
Thanks a bunch going to test it now.
The solution is:
mounted() {
this.$nextTick(async function () {
console.log('get block: ')
console.log('app.vueData vor app.vueData = get() ')
console.log(app.vueData)
//Get is a deferred / asynchronous process / operation
app.vueData = await get("http://localhost:9999/text/1")
console.log('app.vueData nach Zuweisung: ')
console.log(app.vueData)
console.log('JSON.stringify(app.vueData)')
console.log(JSON.stringify(app.vueData))
})
console.log(';)')
}
The caveat was that async had to go in front of function not mounted or this.$nextTick .
You have created a Promise which resolves the data after the completion of your HTTP request but your code is not waiting for this promise to resolve.
You can do 2 things:
1. Use .then()
2. Use async/await (I prefer this because it looks clean)
If you want to use async/await,
mounted() {
this.$nextTick(async function () {
var inputData=[]
//get("http://localhost:9999/text/1", inputData)
//get("http://localhost:9999/text/1").then(inputData)
inputData = await get("http://localhost:9999/text/1")
app.vueData = inputData
console.log(inputData)
console.log(JSON.stringify(inputData))
console.log(';)')
})
}
In this code, you can see that there is async keyword before the function inside this.$nextTick and await keyword before your get method.
If you want to handle the error, you can always use try/catch block.
try {
inputData = await get("http://localhost:9999/text/1");
} catch (e) {
console.log(e);
}
If you're a fan of .then(), your mounted method would look something like this,
mounted() {
this.$nextTick(function () {
var inputData=[]
get("http://localhost:9999/text/1").then(inputData => {
app.vueData = inputData
console.log(inputData)
console.log(JSON.stringify(inputData))
});
console.log(';)')
})
}

Can't access keys in a json that is returned from mongoose fineOne() [duplicate]

This question already has answers here:
Can't access object property of a Mongoose response
(4 answers)
Closed 4 years ago.
I am encountering a weird issue.
I have searched and found a document in my mongoDB using mongoose by using model.findOne() like so:
Model.findOne({
ID: ID
}).then(existingDoc => {
console.log(existingDoc );
res.send(existingDoc );
});
Now, everything works until now, it sends the json I expected to get. The looks like so:
{
"_id": "5bf388cf170a974770c5c942",
"ID": "11/2018",
"date": "2018-11-20T04:08:47.997Z",
"total": {
"total_market_cap": [
64301.06256298704
]
}
}
The problem is that when I try to access these values for example:
console.log(existingDoc.total);
I get undefined. Tried also using:
console.log(existingDoc['total']);
And I still get undefined.
It returned undefined for everything except the _id and __v. like it is an empty object, although it is not.
Can you try to convert it toObject
Model.findOne({
ID: ID
}).then(existingDoc => {
console.log(existingDoc );
let newdoc = existingDoc.toObject();
console.log(newdoc.myProperty)
res.send(existingDoc );
});

Why can Errors not be stringified? [duplicate]

This question already has answers here:
Is it not possible to stringify an Error using JSON.stringify?
(14 answers)
Closed 7 years ago.
Why can Errors not be stringified?
JSON.stringify(new ReferenceError('foo')); // {}
When for example, Date does something more useful:
JSON.stringify(new Date()); // "2015-04-01T10:23:24.749Z"
JavaScript Error objects are not enumerable. You can verify this easily:
new Error('Test').propertyIsEnumerable('message');
// -> false
You can however define your own toJSON function on the error Object:
Object.defineProperty(Error.prototype, 'toJSON', {
value: function () {
return {value: "Test"};
},
configurable: true
});
JSON.stringify(new Error());
-> "{value: "Test"}"

Categories

Resources