Это пример "ajax сервиса", который я использую в своих проектах, вы можете сделать что-то подобное (и я рекомендую использовать Ax ios, как в этом примере)
import axios from 'axios';
class AjaxService {//Simple wrapper for Axios, in order to manually handle errors which aren't 500
/**
* NOTE: This is NOT an abstraction layer, but just a wrapper for Axios. All consuming modules should expect Axio's response format(response.data).
* @public
* @param {string} url
* @param {Object} config
*/
static async post(url, config) {
return await this.shootAjax('post',url, config);
}
/**
* @public
* @param {string} url
* @param {Object} config
*/
static async get(url, config) {
return await this.shootAjax('get',url, config);
}
/**
* @public
* @param {string} key
* @param {string} value
*/
static setHeader(key,value){
axios.defaults.headers.common[key] = value;
}
/**
* @private
* @param {string} method
* @param {string} url
* @param {Object} config
*/
static async shootAjax(method, url, config) {
// debugger;
// url = this.processUrl(url);
let response;
if (method === 'get') {
response = await axios.get(url, config);
} else {
response = await axios.post(url, config);
}
if (response.data.status !== 'ok') {//Manual promise rejection.
const error = new Error(response.data.error);
error.errorCode = response.data.errorCode;
throw error;
}
return response;
}
}
export default AjaxService;
Обратите внимание, что в этом примере у меня есть некоторая ручная обработка ошибок в соответствии со структурой моих ответов API, конечно, вы можете настроить свои собственные.
При таком подходе все, что вам нужно сделать, в "верхнем коде" "ждать функций get / post внутри блока try / catch.