import { JsonpConfig , JsonpPromise , Window } from '../types' ; export default function jsonp ( config ) { return new Promise ( ( resolve , reject ) => { const { url , timeout = 6000 , funcName } = config ; if ( ! funcName ) { reject ( new Error ( 'funcName must exist!' ) ) ; } ; ( < any > window ) [ funcName ! ] = function ( data ) { clean ( ) ; resolve ( data ) ; } ; if ( timeout ) { var timer = setTimeout ( ( ) => { clean ( ) ; reject ( new Error ( `Timeout of ${ timeout } ms exceeded` ) ) ; } , timeout ) ; } function clean ( ) { if ( elem . parentNode ) elem . parentNode . removeChild ( elem ) ; ( < any > window ) [ funcName ! ] = { } ; if ( timer ) clearTimeout ( timer ) ; } let elem = document . createElement ( 'script' ) ; elem . src = url ; let insertPosition = document . getElementsByTagName ( 'script' ) [ 0 ] || document . head ; insertPosition . parentNode ! . insertBefore ( elem , insertPosition ) ; } ) ; }