Вам нужен потребитель вашего API для этого?
// within an async function
const client = new Client();
await client.init();
await client.sendDate();
// or anywhere just using promises
const client = new Client();
client.init().then(() => client.sendDate());
или сам API?
// definition
class Client {
async init() {
const response = await axios.post(this.baseUrl);
this.token = response.data.token;
}
async sendData() {
await this.init(); // call init before sending data
return axios.post(this.baseUrl, {token: this.token})
}
}
// usage somewhere in an async function
const client = new Client();
client.sendDate() // calls init, then sends the data
Возможно, удалите лишние вызовы, если токен не изменяется?
class Client {
async init() {
const response = await axios.post(this.baseUrl);
this.token = response.data.token;
}
async sendData() {
if (!this.token) { // now you'll only call init for missing token
await this.init();
}
return axios.post(this.baseUrl, {token: this.token})
}
}
// usage somewhere in an async function
const client = new Client();
await client.sendDate(); // calls init (only the first time), then sends the data
Обратите внимание, что функции, возвращающие обещание, по своей сути асинхронны, поэтому нет способа получить их результат синхронным способом.Однако мы можем написать асинхронный код, используя async / await, чтобы он синтаксически выглядел (почти) идентично синхронной версии.