refactor: remove nested promise

isekai-main
Barış Soner Uşaklı 1 year ago
parent aff19a6c6b
commit 379ed0e2e8

@ -7,19 +7,20 @@ import { confirm } from 'bootbox';
const baseUrl = config.relative_path + '/api/v3'; const baseUrl = config.relative_path + '/api/v3';
function call(options, callback) { async function call(options, callback) {
options.url = options.url.startsWith('/api') ? options.url = options.url.startsWith('/api') ?
config.relative_path + options.url : config.relative_path + options.url :
baseUrl + options.url; baseUrl + options.url;
if (typeof callback === 'function') { if (typeof callback === 'function') {
xhr(options, callback); xhr(options).then(result => callback(null, result), err => callback(err));
return; return;
} }
return new Promise((resolve, reject) => { try {
xhr(options, function (err, data) { const result = await xhr(options);
if (err) { return result;
} catch (err) {
if (err.message === 'A valid login session was not found. Please log in and try again.') { if (err.message === 'A valid login session was not found. Please log in and try again.') {
return confirm('[[error:api.reauth-required]]', (ok) => { return confirm('[[error:api.reauth-required]]', (ok) => {
if (ok) { if (ok) {
@ -27,14 +28,11 @@ function call(options, callback) {
} }
}); });
} }
return reject(err); throw err;
} }
resolve(data);
});
});
} }
async function xhr_async(options) { async function xhr(options) {
// Normalize body based on type // Normalize body based on type
const { url } = options; const { url } = options;
delete options.url; delete options.url;
@ -87,12 +85,6 @@ async function xhr_async(options) {
response; response;
} }
function xhr(options, callback) {
// then().catch() is not correct here because callback() is called twice when the first then() throws an exception.
// pass onfulfilled and onrejected here, as two parameters of Promise.prototype.then()
xhr_async(options).then(result => callback(null, result), error => callback(error));
}
export function get(route, data, onSuccess) { export function get(route, data, onSuccess) {
return call({ return call({
url: route + (data && Object.keys(data).length ? ('?' + $.param(data)) : ''), url: route + (data && Object.keys(data).length ? ('?' + $.param(data)) : ''),

Loading…
Cancel
Save