I would like to utilize the Promises in my class methods. In Promise antipatterns I read that creating a new promise for each new function is considered to be bad.
However, I don't want to return un-related promises in my project, so I thought of doing something like this:
class MyClass {
async getToken() {
return new Promise(
(resolve, reject) => {
// . . .
const token_str = '<response_from_http_request>';
resolve(token_str);
}
)
}
async doSomething(token) {
return new Promise(
(resolve, reject) => {
const result = // . . .
resolve(result);
}
)
}
async doAnotherSomething(token) {
return new Promise(
(resolve, reject) => {
const result = // . . .
resolve(result);
}
)
}
}
Then I would use it like this:
let instance = new MyClass();
(async () => {
const token = await instance.getToken();
const result1 = await instance.doSomething(token);
console.log(result1);
const result2 = await instance.doAnotherSomething(token);
console.log(result2);
})();
Does this seem like a valid way to do this, or is this an antipattern too? And if so, how can I avoid writing code like this?
EDIT: What if I need to make several sequential http calls, perform some actions on the results and then return a Promise based on it?
The way I understand, if I don't make a new Promise, I have to return the one made by the got.js
library, which includes the http response data.
Instead, I want to return a Promise which contains the result of my class method.
Example: async getCityWeather( city_name ) {
return new Promise(
(resolve, reject) => {
// get the city id based on its name
const city_id = await got(`https://my-api/getCityIdByName/${city_name}`);
// now get the weather info for the city with id `cityid`
const weather_info = await got(`https://my-api/weatherById/${city_id}`);
// make an object to return
const temperature = {
weather_info.temp_min,
weather_info.temp_max,
}
resolve(temperature);
// ... all error handling are omitted
}
)
}
I don't want to return a Promise that contains got.js return values, I want to return my values based on the http request calls.