Inspired from https://github.com/webmodules/jsonp
Install via NPM:
npm i @seven_y_q_guo/jsonp
const jsonp = require("@seven_y_q_guo/jsonp"); // or import jsonp from '@seven_y_q_guo/jsonp';
jsonp('http://jsfiddle.net/echo/jsonp?name=seven', {
name: 'hello',
success: (info) => {
console.log(info); // {name: 'seven'}
},
error: (error) => {
console.log(error); // handle kinds of errors like timeout, 404, etc.
}
});
url
(String
) url to fetchopts
(Object
)success
handle successerror
handle errorparam
(String
) name of the query string parameter to specify the callback (defaults tocallback
)timeout
(Number
) how long after a timeout error is emitted.0
or other falsy value to disable (defaults to30000
)prefix
(String
) prefix for the global callback functions that handle jsonp responses (defaults to__jp
)name
(String
) optional: name of the global callback functions that handle jsonp responses, will generate__jp + incremented
counter if not passing specific name
Returns a function that, when called, will cancel the in-progress jsonp request
(success
& error
won't be called any more).
function fetchJson(url, opts = {}) {
return new Promise((resolve, reject) => {
jsonp(url, {
...opts,
success: resolve,
error: reject
});
})
}
fetchJson('http://jsfiddle.net/echo/jsonp?name=seven').then(res => {
console.log(res);
}).catch(err => {
console.log(err);
});
MIT