Compare commits

...

2 Commits

Author SHA1 Message Date
Barış Soner Uşaklı
66354902ec refactor: don't use a xhr_async function
dont wrap async xhr in new Promise
2023-09-25 10:36:38 -04:00
pkuanvil-uid1
3b9be63dc0 fix: properly wrap promise to callback-style function
Async function xhr use a mixture of await and callback, which is not correct when an exception is thrown before callback happens. Use only async/await for it and create a new callback-style wrapper.
2023-09-23 19:32:12 +08:00

View File

@@ -7,36 +7,32 @@ import { confirm } from 'bootbox';
const baseUrl = config.relative_path + '/api/v3';
function call(options, callback) {
async function call(options, callback) {
options.url = options.url.startsWith('/api') ?
config.relative_path + options.url :
baseUrl + options.url;
if (typeof callback === 'function') {
xhr(options, callback);
xhr(options).then(result => callback(null, result), err => callback(err));
return;
}
return new Promise((resolve, reject) => {
xhr(options, function (err, data) {
if (err) {
if (err.message === 'A valid login session was not found. Please log in and try again.') {
return confirm('[[error:api.reauth-required]]', (ok) => {
if (ok) {
ajaxify.go('login');
}
});
try {
const result = await xhr(options);
return result;
} catch (err) {
if (err.message === 'A valid login session was not found. Please log in and try again.') {
return confirm('[[error:api.reauth-required]]', (ok) => {
if (ok) {
ajaxify.go('login');
}
return reject(err);
}
resolve(data);
});
});
});
}
throw err;
}
}
async function xhr(options, cb) {
async function xhr(options) {
// Normalize body based on type
const { url } = options;
delete options.url;
@@ -79,16 +75,14 @@ async function xhr(options, cb) {
if (!res.ok) {
if (response) {
return cb(new Error(isJSON ? response.status.message : response));
throw new Error(isJSON ? response.status.message : response);
}
return cb(new Error(res.statusText));
throw new Error(res.statusText);
}
cb(null, (
isJSON && response && response.hasOwnProperty('status') && response.hasOwnProperty('response') ?
response.response :
response
));
return isJSON && response && response.hasOwnProperty('status') && response.hasOwnProperty('response') ?
response.response :
response;
}
export function get(route, data, onSuccess) {