javascript: make utils.ajax() return a promise
This allow to use `await ajax(…)`, and still have Rails manage the request, insert the proper headers and tokens, etc.
This commit is contained in:
parent
0c944ceeb2
commit
ec2199f7b1
1 changed files with 17 additions and 1 deletions
|
@ -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;
|
||||
|
|
Loading…
Reference in a new issue