I have an array where I need to call an API endpoint for each index. Once that is resolved I need to append it in that element. I want to return the updated array once this gets completed for each index of the array.
I tried using async-await in this way
// Let input be [{'x': 1, 'y': 2}, {'x': 11, 'y': 22}, ...]
async function hello(input) {
await input.forEach(element => {
fetch(url, options)
.then((res) => {
element['z'] = res
})
})
return input
}
I need to use this function to update my state
hello(data)
.then((res: any) => {
this.setState((prevState) => ({
...prevState,
inputData: res,
}))
})
The issue is that I need one more forced render for key 'z' to show.
How to resolve this?
I don't have much experience using async await so I am not sure if I am using it correctly.
The correct way is to use Promise.all and return the promise to be used by the caller function since you want the entire updated input value to be set in state.
In your case forEach doesn't return a promise so await on it is useless.
Also if you use await within the forEach function, you need to be able provide away to let the hello function's .then method call when all promises have resolved. Promise.all does that for you
function hello(input) {
const promises = [];
input.forEach(element => {
promises.push(
fetch(url, options)
.then(res => res.json()
.then((result) => {
// return the updated object
return {...element, z: result};
})
)
});
return Promise.all(promises);
}
...
hello(data)
.then((res: any) => {
this.setState((prevState) => ({
...prevState,
inputData: res,
}))
})
P.S. Note that the response from fetch also will need to be called with res.json()
async/await won't work in loops which uses callback(forEach, map, etc...)
You can achieve your result using for..of loop.
Try this and let me know if it works.
function getResult() {
return new Promise((resolve) => {
fetch(url, options)
.then((res) => {
return resolve(res);
})
})
}
async function hello(input) {
for (let element of input) {
let res = await getResult(element);
element['z'] = res;
}
}
Related
Hello I have this async function which retrieves user profile and repositories through github api and returns them in an object.
And I want to convert this to a promise based function by using promise chaining (without any helper methods).
async function getUser(user) {
const profileResponse = await fetch(`https://api.github.com/users/${user}`);
const profileData = await profileResponse.json();
const repoResponse = await fetch(`https://api.github.com/users/${user}/repos`);
const reposData = await repoResponse.json();
// returning an object with profile and data
return {
profile:profileData,
repos:repoData,
};
}
//Calling the function here.
getUser("abufattah").then((res) => console.log(res));
I have managed to get it done using two helper functions and promise.all() method.
But how can I achieve the same thing by using promise chaining without any helper functions.
//Helper function 1: returns a promise with user profile data.
function getUserProfile(user) {
return fetch(`https://api.github.com/users/${user}`)
.then((res) =>res.json());
}
//Helper function 2: returns a promise with user repositories data.
function getUserRepos(user) {
return fetch(`https://api.github.com/users/${user}/repos?per_page=5&sort=created`)
.then((res) => res.json());
}
//Main function
function getUserWithPromise(user) {
return new Promise((resolve) => {
let profile = getUserProfile(user);
let repos = getUserRepos(user);
Promise.all([profile, repos]).then((values) => {
resolve({ profile: values[0], repos: values[1] });
});
});
}
// calling the function here
getUserWithPromise("abufattah").then((res) => console.log(res));
Transformation of async/await syntax to .then() calls is quite mechanical, especially if it doesn't involve any control flow syntax (loops or conditionals):
function getUser(user) {
return fetch(`https://api.github.com/users/${user}`).then(profileResponse => {
return profileResponse.json().then(profileData => {
return fetch(`https://api.github.com/users/${user}/repos`).then(repoResponse => {
return repoResponse.json().then(reposData => {
// returning an object with profile and data
return {
profile:profileData,
repos:repoData,
};
});
});
});
});
}
But there's no good reason to write code like that. If it's just that your target environment does not support async/await, let a transpiler do the transformation.
You can:
//Main function
function getUserWithPromise(user) {
return Promise.all([
fetch(`https://api.github.com/users/${user}`).then((res) =>res.json()),
fetch(`https://api.github.com/users/${user}/repos?per_page=5&sort=created`).then((res) => res.json())
]).then(([result1, result2]) => ({ profile: result1, repos: result2 }));
}
// calling the function here
getUserWithPromise("abufattah").then((res) => console.log(res));
Chain:
function getUserWithPromise(user) {
return fetch(`https://api.github.com/users/${user}`)
.then((res) => {
return fetch(`https://api.github.com/users/${user}/repos?per_page=5&sort=created`).then((fetch2Result) => ([res.json(), fetch2Result.json()]))
}).then(([result1, result2]) => ({ profile: result1, repos: result2 }))
}
// calling the function here
getUserWithPromise("abufattah").then((res) => console.log(res));
I have this test I made just to check an API, but then i tryied to add an URL from a second fetch using as parameter a value obtained in the first fetch and then return a value to add in the first fecth. The idea is to add the image URL to the link. thanks in advance.
function script() {
const url = 'https://pokeapi.co/api/v2/pokemon/?offset=20&limit=20'
const result = fetch(url)
.then( (res)=>{
if(res.ok) {
return res.json()
} else {
console.log("Error!!")
}
}).then( data => {
console.log(data)
const main = document.getElementById('main');
main.innerHTML=`<p><a href='${data.next}'>Next</a></p>`;
for(let i=0; i<data.results.length;i++){
main.innerHTML=main.innerHTML+`<p><a href=${getImageURL(data.results[i].url)}>${data.results[i].name}</a></p>`;
}
})
}
async function getImageURL(imgUrl) {
const resultImg = await fetch(imgUrl)
.then( (res)=> {
return res.json()
})
.then (data => {
console.log(data.sprites.other.dream_world.front_default);
})
return resultImg.sprites.other.dream_world.front_default;
}
In general, don't mix .then/.catch handlers with async/await. There's usually no need, and it can trip you up like this.
The problem is that your fulfillment handler (the .then callback) doesn't return anything, so the promise it creates is fulfilled with undefined.
You could return data, but really just don't use .then/.catch at all:
async function getImageURL(imgUrl) {
const res = await fetch(imgUrl);
if (!res.ok) {
throw new Error(`HTTP error ${res.status}`);
}
const resultImg = await res.json();
return resultImg.sprites.other.dream_world.front_default;
}
[Note I added a check of res.ok. This is (IMHO) a footgun in the fetch API, it doesn't reject its promise on HTTP errors (like 404 or 500), only on network errors. You have to check explicitly for HTTP errors. (I wrote it up on my anemic old blog here.)]
There's also a problem where you use getImageURL:
// Incorrent
for (let i = 0; i < data.results.length; i++) {
main.innerHTML=main.innerHTML+`<p><a href=${getImageURL(data.results[i].url)}>${data.results[i].name}</a></p>`;
}
The problen here is that getImageURL, like all async functions, returns a promise. You're trying to use it as those it returned the fulfillment value you're expecting, but it can't — it doesn't have that value yet.
Instead, you need to wait for the promise(s) youre creating in that loop to be fulfilled. Since that loop is in synchronous code (not an async function), we'd go back to .then/.catch, and since we want to wait for a group of things to finish that can be done in parallel, we'd do that with Promise.all:
// ...
const main = document.getElementById('main');
const html = `<p><a href='${data.next}'>Next</a></p>`;
Promise.all(data.results.map(async ({url, name}) => {
const realUrl = await getImageURL(url);
return `<p><a href=${realUrl}>${name}</a></p>`;
}))
.then(paragraphs => {
html += paragraphs.join("");
main.innerHTML = html;
})
.catch(error => {
// ...handle/report error...
});
For one, your
.then (data => {
console.log(//...
at the end of the promise chain returns undefined. Just remove it, and if you want to console.log it, do console.log(resultImg) in the next statement/next line, after await.
This the final version that accomplish my goal. Just want to leave this just in case someone finds it usefull. Thanks for those who answer!
function script() {
const url = 'https://pokeapi.co/api/v2/pokemon/?offset=20&limit=20'
const result = fetch(url)
.then( (res)=>{
if(res.ok) {
return res.json()
} else {
console.log("Error!!")
}
}).then( data => {
console.log(data)
const main = document.getElementById('main');
main.innerHTML=`<p><a href='${data.next}'>Proxima Página</a></p>`;
Promise.all(data.results.map(async ({url, name}) => {
const realUrl = await getImageURL(url);
return `<div><a href=${realUrl}>${name}</a></div>`;
}))
.then(paragraphs => {
main.innerHTML=main.innerHTML+paragraphs;
})
.catch(error => {
console.log(error);
});
})
}
async function getImageURL(imgUrl) {
const res = await fetch(imgUrl);
if(!res.ok) {
throw new Error(`HTTP Error ${res.status}`)
}
const resultImg = await res.json();
return resultImg.sprites.other.dream_world.front_default
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to push data from promise to array (coursesArray) and then use the array values else where. I am using node-fetch library to query the API. Currently when i log array inside the promise, it has values(coursesOne) however when i log the array outside the promise, it is empty(coursesTwo). How do i go about implementing the ideal solution so that coursesArray is filled with data when getCoursesForSitemap() executes
Here is what i have implemented so far
const coursesArray = [];
const getCoursesForSitemap = () => {
fetch(coursesUrl)
.then(res => res.json())
.then(json => {
json.courses.results.map(course => {
return coursesArray.push(course.slug);
});
console.log('coursesOne', coursesArray);
})
.catch(error => {
console.log(error);
});
};
getCoursesForSitemap();
console.log('coursesTwo', coursesArray);
Refactoring your code to use async/await, and not making it mutate the out-of-closure/global variable, this should work for you.
const getCoursesForSitemap = async () => {
const result = await fetch(coursesUrl);
const json = await result.json();
return json.courses.results.map(course => course.slug);
};
const coursesArray = await getCoursesForSitemap();
console.log('coursesTwo', coursesArray);
In case your environment doesn't support top-level async/await, you'll need to execute the async code in e.g. an IIFE:
(async function() {
const coursesArray = await getCoursesForSitemap();
console.log('coursesTwo', coursesArray);
}());
(That function will also return a promise you can .then() or await on...)
You are trying to log the values before they are resolved from your promise. That's why it's not working. You need to wait for the Promise to be resolve before trying to show them.
You also need to return the promise .
const coursesArray = [];
const getCoursesForSitemap = () => {
return fetch(coursesUrl)
.then(res => res.json())
.then(json => {
json.courses.results.forEach(course => {
return coursesArray.push(course.slug);
});
console.log('coursesOne', coursesArray);
})
.catch(error => {
console.log(error);
});
};
getCoursesForSitemap().then(() => {
console.log('coursesTwo', coursesArray);
});
I've also changed the map function you use for a forEach since you don't need to change the value of the json.courses.results array.
I have a service to get a list from server. But in this list I need to call another service to return the logo img, the service return ok, but my list remains empty. What i'm did wrong ?
I tried to use async/await in both services
I tried to use a separate function to get the logos later, but my html don't change.
async getOpportunitiesByPage(_searchQueryAdvanced: any = 'active:true') {
this.listaOportunidades = await this._opportunities
.listaOportunidades(this.pageSize, this.currentPage, _searchQueryAdvanced)
.toPromise()
.then(result => {
this.totalSize = result['totalElements'];
return result['content'].map(async (opportunities: any) => {
opportunities.logoDesktopUrl = await this.getBrand(opportunities['brandsUuid']);
console.log(opportunities.logoDesktopUrl);
return { opportunities };
});
});
this.getTasks(this.totalSize);
}
No errors, just my html don't change.
in my
console.log(opportunities.logoDesktopUrl);
return undefined
but in the end return filled.
info:
Angular 7
server amazon aws.
await is used to wait for promise.
You should return promise from getBrand if you want to wait for it in getOpportunitiesByPage.
Change the getBrand function as following.
getBrand(brandsUuid): Observable<string> {
this.brandService.getById(brandsUuid).pipe(map(res => {
console.log(res.logoDesktopUrl); return res.logoDesktopUrl;
}))
}
Change opportunities.logoDesktopUrl = await this.getBrand(opportunities['brandsUuid']); to opportunities.logoDesktopUrl = await this.getBrand(opportunities['brandsUuid']).toPromise();
Please make sure you imported map from rxjs/operators.
At first,when you await, you should not use then.
At second, async/await runs only with Promises.
async getOpportunitiesByPage(_searchQueryAdvanced: any = 'active:true') {
const result = await this._opportunities
.listaOportunidades(this.pageSize, this.currentPage, _searchQueryAdvanced)
.toPromise();
this.totalSize = result['totalElements'];
this.listaOportunidades = result['content'].map(async (opportunities: any) => {
opportunities.logoDesktopUrl = await this.getBrand(opportunities['brandsUuid']);
console.log(opportunities.logoDesktopUrl);
return opportunities;
});
this.getTasks(this.totalSize);
}
getBrand(brandsUuid) {
return new Promise((resolve, reject) => {
this.brandService.getById(brandsUuid).subscribe(res => {
console.log(res.logoDesktopUrl);
return resolve(res.logoDesktopUrl);
}, err => {
return reject(err);
});
});
}
But, because rxjs is a used in Angular, you should use it instead of async/await :
getOpportunitiesByPage: void(_searchQueryAdanced: any = 'active:true') {
this._opportunities.listaOportunidades(this.pageSize, this.currentPage, _searchQueryAdvanced).pipe(
tap(result => {
// we do that here because the original result will be "lost" after the next 'flatMap' operation
this.totalSize = result['totalElements'];
}),
// first, we create an array of observables then flatten it with flatMap
flatMap(result => result['content'].map(opportunities => this.getBrand(opportunities['brandsUuid']).pipe(
// merge logoDesktopUrl into opportunities object
map(logoDesktopUrl => ({...opportunities, ...{logoDesktopUrl}}))
)
),
// then we make each observable of flattened array complete
mergeAll(),
// then we wait for each observable to complete and push each result in an array
toArray()
).subscribe(
opportunitiesWithLogoUrl => {
this.listaOportunidades = opportunitiesWithLogoUrl;
this.getTasks(this.totalSize);
}, err => console.log(err)
);
}
getBrand(brandsUuid): Observable<string> {
return this.brandService.getById(brandsUuid).pipe(
map(res => res.logoDesktopUrl)
);
}
Here is a working example on stackblittz
There might be a simpler way to do it but it runs :-)
I'm trying to prefetch multiple image before navigating to another screen, but returnedStudents all undefined.
prepareStudentImages = async (students) => {
let returnedStudents = students.map(student => {
Image.prefetch(student.image)
.then((data) => {
...
})
.catch((data) => {
...
})
.finally(() => {
return student;
});
});
await console.log(returnedStudents); // ----> all items undefined
}
There are a couple of things to fix with this:
1) Your map() function does not return anything. This is why your console log is undefined.
2) Once your map functions work, you are logging an array of promises. To deal with multiple promises (an array), you can use Promise.all().
So I think to fix this, you can do:
prepareStudentImages = async (students) => {
const returnedStudents = students.map(student =>
Image.prefetch(student.image)
.then((data) => {
...
})
.catch((data) => {
...
})
.finally(() => {
return student
})
)
console.log(returnedStudents) // log the promise array
const result = await Promise.all(returnedStudents) // wait until all asyncs are complete
console.log(result) // log the results of each promise in an array
return result
}