From 379ed0e2e81f17678c2ebcc6bc7a7a7a00fbb812 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bar=C4=B1=C5=9F=20Soner=20U=C5=9Fakl=C4=B1?= Date: Mon, 25 Sep 2023 10:49:14 -0400 Subject: [PATCH] refactor: remove nested promise --- public/src/modules/api.js | 38 +++++++++++++++----------------------- 1 file changed, 15 insertions(+), 23 deletions(-) diff --git a/public/src/modules/api.js b/public/src/modules/api.js index 77e52148ca..f510586549 100644 --- a/public/src/modules/api.js +++ b/public/src/modules/api.js @@ -7,34 +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_async(options) { +async function xhr(options) { // Normalize body based on type const { url } = options; delete options.url; @@ -87,12 +85,6 @@ async function xhr_async(options) { 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) { return call({ url: route + (data && Object.keys(data).length ? ('?' + $.param(data)) : ''),