If you happens to want to convert jQuery’s ajax function into promise style using ES6 promise. Here is an example for you:
utils.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import { Promise } from 'es6-promise' export function ajaxPostPromise(url, postData) { return new Promise((resolve, reject) => { $.ajax({ url : url, type: "POST", data : postData, dataType: "json", success: (data, textStatus, jqXHR) =>{ resolve(data); }, error: (jqXHR, textStatus, errorThrown){ reject(errorThrown); } }); }); } |
Then you can use ajaxPostPromise in this way:
app.js
1 2 3 4 5 6 7 8 9 | import { ajaxPostPromise } from './utils' ajaxPostPromise("http://example.com/api/get_product", {page:1}) .then( (data) => { // display the data }) .catch( (e) => { // handle the error }) |
That’s it!
You can apply the same principle in converting other callback-style library into promise!
p.s. If you are looking for native and promise way to call your API, you may also check out fetch.