@seven_y_q_guo/jsonp

1.12.0 • Public • Published

<CircleCI>

[build-your-own] JSONP

Inspired from https://github.com/webmodules/jsonp

Installation

Install via NPM:

npm i @seven_y_q_guo/jsonp

Usage

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.
  }
});

API

jsonp(url, opts)

  • url (String) url to fetch
  • opts (Object)
    • success handle success
    • error handle error
    • param (String) name of the query string parameter to specify the callback (defaults to callback)
    • timeout (Number) how long after a timeout error is emitted. 0 or other falsy value to disable (defaults to 30000)
    • 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).

Want Promise?

You can implement easily

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);
});

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i @seven_y_q_guo/jsonp

Weekly Downloads

1

Version

1.12.0

License

MIT

Unpacked Size

17.3 kB

Total Files

12

Last publish

Collaborators

  • seven_y_q_guo