Merge pull request #4919 from betagouv/ajax-as-promise

javascript: make utils.ajax() return a promise
This commit is contained in:
Paul Chavard 2020-03-19 18:55:27 +01:00 committed by GitHub
commit 6ea64c28e1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -3,7 +3,7 @@ import $ from 'jquery';
import debounce from 'debounce';
export { debounce };
export const { fire, ajax } = Rails;
export const { fire } = Rails;
export function show(el) {
el && el.classList.remove('hidden');
@ -45,6 +45,22 @@ export function delegate(eventNames, selector, callback) {
);
}
export function ajax(options) {
return new Promise((resolve, reject) => {
Object.assign(options, {
success: (response, statusText, xhr) => {
resolve({ response, statusText, xhr });
},
error: (response, statusText, xhr) => {
let error = new Error(`Erreur ${xhr.status} : ${statusText}`);
Object.assign(error, { response, statusText, xhr });
reject(error);
}
});
Rails.ajax(options);
});
}
export function getJSON(url, data, method = 'get') {
incrementActiveRequestsCount();
data = method !== 'get' ? JSON.stringify(data) : data;