JSONP 通用函式封裝

apy發表於2019-01-25
function jsonp({url, params, callback}) {
      return new Promise((resolve, reject) => {
        let script = document.createElement(`script`)
        // callback 讓伺服器端呼叫,並且將資料傳遞進來
        window[callback] = function (data) {
          resolve(data)
          document.body.removeChild(script)
        }
        params = {...params, callback}
        const arr = []
        for (let key in params) {
          arr.push(`${key}=${params[key]}`)
        }
        script.src = `${url}?${arr.join(`&`)}`
        document.body.appendChild(script)
      })
    }

    function synchronize(urls) {
      return urls.map((url,i) => jsonp({url, params: {}, callback: `show` + i}))
    }

      const ajurl = [
        `http://api.douban.com/v2/movie/in_theaters`, 
        `http://api.douban.com/v2/movie/top250`
      ]

      Promise.all(synchronize(ajurl))
        .then(result => {
          for (let val of result) {
            console.log(val)
          }
        })

相關文章