[feat] promise based jsonp

pull/1/head
Ziqiang Li 2017-08-07 20:24:25 +08:00
parent dd269a26bd
commit cc175aca05
4 changed files with 119 additions and 1 deletions

8
.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Created by .ignore support plugin (hsz.mobi)
.idea/
.classpath
.project
.settings/
node_modules
.DS_Store
*.log

View File

@ -1 +1,23 @@
# simple-jsonp-promise
# simple-jsonp-promise
## Installation
``` bash
yarn add simple-jsonp-promise
```
## Example
``` bash
import jsonp from 'simple-jsonp-promise'
let options = {
params:{
a : 1,
b : 2
},
jsonp : 'callback',
prefix : '__jp',
timeout : 15000
}
let response = await jsonp('https://localhost/api.jsonp' , options);
```

65
index.js Normal file
View File

@ -0,0 +1,65 @@
/**
* Created by lizq on 2017/8/7
*/
// Callback index.
let count = 0;
/**
* JSONP handler
*
* Options:
* - prefix {String} callback prefix (defaults to `__jp`)
* - jsonp {String} qs jsonpeter (defaults to `callback`)
* - timeout {Number} how long after the request until a timeout error
* is emitted (defaults to `15000`)
*/
let jsonp = function( url, options ) {
options = options || {};
let prefix = options.prefix || '__jp';
let jsonp = options.jsonp || 'callback';
let params = options.params || {};
let timeout = options.timeout ? options.timeout : 15000;
let target = document.getElementsByTagName( 'script' )[ 0 ] || document.head;
let script;
let timer;
let cleanup;
let promise;
let noop = function() {};
// Generate a unique id for the request.
let id = prefix + (count++);
cleanup = function() {
// Remove the script tag.
if ( script && script.parentNode ) {
script.parentNode.removeChild( script );
}
window[ id ] = noop;
if ( timer ) { clearTimeout( timer ); }
};
promise = new Promise( ( resolve, reject ) => {
if ( timeout ) {
timer = setTimeout( function() {
cleanup();
reject( new Error( 'Timeout' ) );
}, timeout );
}
window[ id ] = function( data ) {
cleanup();
resolve( data );
};
params[ jsonp ] = id;
for ( let key in params ) {
url += (~url.indexOf( '?' ) ? '&' : '?') + key + '=' + encodeURIComponent( params[ key ] );
}
url = url.replace( '?&', '?' );
// Create script.
script = document.createElement( 'script' );
script.src = url;
script.onerror = function() {
cleanup();
reject( new Error( 'Network Error' ) );
};
target.parentNode.insertBefore( script, target );
} );
return promise;
};
export default jsonp;

23
package.json Normal file
View File

@ -0,0 +1,23 @@
{
"name": "simple-jsonp-promise",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/liziqiang/simple-jsonp-promise.git"
},
"keywords": [
"jsonp",
"promise"
],
"author": "Ziqiang Li <ziqiang.lee@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/liziqiang/simple-jsonp-promise/issues"
},
"homepage": "https://github.com/liziqiang/simple-jsonp-promise#readme"
}