Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
Hey guys Im making a api call and getting a response I have not yet encountered . my api call is basic and looks like
async function getStudents(){
const response = await fetch('url');
const studentData = response.json();
console.log(studentData)
Promise { : "pending" } : "fulfilled" : Object {
students: (25) […] }
and these are the results I get, Normally I could do something like studentData.students to get that object but nothing seems to get the correct object. what am I doing wroing?
Use something like this :
async function getStudents(){
fetch('url')
.then(response => response.json())
.then(data => console.log(data));
.catch(error=>console.log(error,"error occured"));
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 days ago.
Improve this question
I encountered a strange behavior when I defined 4 Promises which the last one is described as just rejected and when I tried to run each promise separately, the last one is fired! This will fire rejection especially when I want to run all Promises (_1 _2 _3) in Promise.all().
I wanted to use catch() for promise_2 in Promise.all([promise.catch((err)=>console.log(err))]).then(...) from handling the error happend in promise_2 without cancelling the operation of other Promises
Thx
const asyncFunction=(timer,callback)=>{
setTimeout(() => {
callback(10)
}, timer);
}
const promise_1=new Promise((resolved,reject)=>{
const date=new Date().getSeconds()
date%2===0?asyncFunction(1000,(value)=>resolved(value)):reject(new Error("hello"))
})
const promise_2=new Promise((resolved,reject)=>{
asyncFunction(2000,(value)=>resolved(value))
})
const promise_3=new Promise((resolved,reject)=>{
asyncFunction(3000,(value)=>resolved(value))
})
const promise_4=new Promise((resolved,reject)=>{
reject(new Error("i am bad"))
})
promise_1.then((value)=>console.log(value))
first in Node
C:\Program Files\nodejs\node.exe .\test.js
Process exited with code 1
Uncaught Error Error: I am bad<--------------------------what is it?this is for promise_4 ,while I didn't call it
second in V8
See here
[in V81
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm getting some mock data from a mock endpoint, using JQuery and promises.
Just for the sake of it, I want to try and make it work with async/await.
I think I managed to find some code that works, although, I don't get the same output ( in chrome browser) in the console.
Here are the two pieces of code :
import $ from 'jquery';
let myPromise = $.get("http://5e2f41529c29c900145db22d.mockapi.io/test/users");
myPromise
.then(
(data) => {
console.log('Success promises: ', data);
}
)
.catch(
(error) => {
console.log('Error : ', error.responseText);
}
);
and
// same as above but with async/await
import $ from 'jquery';
let getUsersFromEndPoint = async function (){
try {
let users = await $.get("http://5e2f41529c29c900145db22d.mockapi.io/test/users");
console.log('Success Async: ' + users);
} catch (error) {
console.log('Error : ', error.responseText);
}
};
getUsersFromEndPoint();
And they output :
I'm not sure what the difference is.
Does anyone know why i get a different output ? and what they both "mean" ?
Thank you !
Both the promise-based code and the async/await are correct, and do the same thing, except a small (and therefore hard-to-spot) difference.
The promise-based version's logger code:
console.log('Success promises: ', data);
...logs the result as you expect.
However, in the async function, the console.log contains a + operator, that casts its second operand (the data) into a string, so all objects get transformed into "[object Object]":
console.log('Success Async: ' + users);
Pass data as the second argument of console.log (as you've done with the promise version), and you'll get the expected result.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I saw a piece of code that looks funny to me. It feels like there are multiple things wrong here. Am I seeing a ternary here returning an error rather than a value? Shouldn't this therefore be an if-else?
const aData = await response.json();
return await new Promise((resolve, reject) => {
(aData.title === aName)
? resolve('A data was found')
: reject(new Error('Incorrect data was returned'));
});
Both resolve and reject just return the value undefined, and your callback function doesn't return anything at all. Using a ternary operator to make it a single expression is rather useless.
For clarity, you should better write
if (aData.title === aName) resolve('A data was found');
else reject(new Error('Incorrect data was returned'));
although really you shouldn't be using the new Promise constructor here at all. Just
const aData = await response.json();
if (aData.title !== aName) throw new Error('Incorrect data was returned');
else return 'A data was found';
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I implemented a function using async and it doesn't work. It always resolves immediately and result is always undefined.
Here is the original async version:
async function validateOne(item, type, state) {
const validation = VALIDATIONS[type]
const result = !(await validation.check(state[item.name].value, state))
return result || validation.message
}
I couldn't figure out why it wasn't working so I rewrote it using a Promise and it works fine.
function validateOne(item, type, state) {
const validation = VALIDATIONS[type]
return new Promise(resolve => {
validation.check(state[item.name].value, state).then(result =>
resolve(result || validation.message)
)
})
}
I'm confused because in my mind these two implementations should be identical (clearly they are not). Hopefully it is something obvious, thanks in advance for any insights!
I think your async function contains an unnecessary logical not ! operator. Try:
async function validateOne(item, type, state) {
const validation = VALIDATIONS[type]
const result = await validation.check(state[item.name].value, state)
return result || validation.message
}
Alternatively, this can be shortened to:
async function validateOne(item, type, state) {
const validation = VALIDATIONS[type]
return (await validation.check(state[item.name].value, state)) || validation.message
}
Nevermind, I had a typo where one version was negating result and the other wasn't!! They are in fact, apart from that typo, identical!
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am using the http request library got. With this package, http connections are asynchronous, fast, and easy to type out. The "got"cha is that got is a promisified package, which brings up several challenges for me. One is that I don't know how to pass around a reference to the got.
What I need to do is use got together with file streams to download the page contents of several url's. Upon completion of all of these streams, I want to continue in the code.
In this example instead of making an array of promises I am getting an array of response objects.
const getFile = (fileUrl) => {
return new Promise((resolve) => {
got.stream(fileUrl).pipe(fs.createWriteStream(path.basename(fileUrl)))
.on('finish', () => {
successMessage('downloaded ' + fileUrl + '!');
resolve();
});
});
};
// create an array of these got promises
let promises = []
for (let file of body.files) {
promises.push(getFile(file));
}
The reason the getFile helper exists is to wrap the got in a promise so that after performing all of the gots, I can use a promise.all call:
// after all got's have executed
promises.all(promises).then(() => {
console.log('all promises resolved');
}
Looking for assistance understanding how to change the first snippet so that promises.all behaves as anticipated.
The Promise aggregation function is called Promise.all() not promises.all().