Created
August 10, 2020 16:59
-
-
Save SharpSeeEr/f75e1b38b786c643a4e5aa2421eccb7e to your computer and use it in GitHub Desktop.
Nested Promise and Formatting Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Formatting { | |
private getCountriesQuery(skip: number, limit: number, order: string, searchName: string) { | |
const Continentscountriescities_Country = Parse.Object.extend('Continentscountriescities_Country'); | |
const query = new Parse.Query(Continentscountriescities_Country); | |
query.limit(limit); // limit to at most 10 results | |
query.skip(skip); // skip the first 10 results | |
const orders: string[] = order.split(','); | |
orders.map(o => { | |
if (o.startsWith('-')) { | |
query.descending(o.replace('-', '')); // Sorts the results in descending order by the views field | |
} else { | |
query.ascending(o); // Sorts the results in ascending order by the likes field | |
} | |
}); | |
if (searchName) { | |
query.skip(0); | |
query.limit(100); | |
query.startsWith('name', searchName); // name starts with "search field2" | |
} | |
return query; | |
} | |
public fetchCountriesFromApiParser(skip = 0, limit = 10, order = 'code', searchName: string) { | |
return new Promise<ICountry[]>((resolve, reject) => { | |
const query = this.getCountriesQuery(skip, limit, order, searchName); | |
function transformCountry(country: any) { | |
return country.get('languages') | |
.query() | |
.find() | |
.then(async language => { | |
// Do lang.get(string) return promises? | |
return await Promise.all(language.map(lang => `${lang.get('name')} [${lang.get('code')}]`)); | |
}) | |
.then(async languages => { | |
return { languages, timezone: await country.get('timezones').query().find() }; | |
}) | |
.then(({languages, timezone}) => { | |
return new Country( | |
undefined, | |
country.id, | |
country.get('name'), | |
country.get('code'), | |
country.get('native'), | |
country.get('phone'), | |
country.get('capital'), | |
country.get('currency'), | |
country.get('emoji'), | |
country.get('emojiU'), | |
country.get('geonameid'), | |
languages.toString(), | |
JSON.stringify(timezone.map(tz => tz.get('TimeZone'))), | |
country.get('continent'), | |
country.get('createdAt'), | |
country.get('updatedAt'), | |
false, | |
country.get('provinces')); | |
}); | |
} | |
query.find().then(results => { | |
Promise.all(results.map(country => transformCountry(country))) | |
.then(res => resolve(res)); | |
}, error => { | |
reject(error); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment