Promise is a container that provides a step of operation. In this container, there are two stages that cannot be changed. The first stage is Pending, and the second stage is the result stage, which includes two results: Fulfilled and Rejected.
These two results will not change. Then after the result is finished, the corresponding result will be executed using then.
new Promise((resolve,reject)=>{ Corresponding operations if(Asynchronous operation succeeded){ resolve(value) }else{ reject(error) } }).then(value=>{ // Operation after success},error=>{ // Operation after failure})
Use Promise to encapsulate jsonp method
import originJSONP from 'jsonp' // At this time, Url does not have parameters. We let data become a parameter. Data is configured separately when defining specific contents.export default function jsonp(url, data, option) { // Check whether the url has a question mark means that you only add a question mark when adding the parameters for the first time, and the rest is to add & url += (('?') < 0 ? '?' : '&') + param(data) return new Promise((resolve, reject) => { originJSONP(url, option, (err, data) => { if (!err) { resolve(data) } else { reject(err) } }) }) } // traverse the data, assuming that data is an arrayfunction param(data) { let url = '' for (var k in data) { let value = data[k] !== undefined ? data[k] : '' url += `&${k} = ${encodeURIComponent(value)}` } //Delete the first & symbol return url ? (1) : '' }
Define a configuration file that is repeated more frequently
export const commonParams = { g_tk: 5381, inCharset: 'utf-8', outCharset: 'utf-8', notice: 0, format: 'jsonp' } // The default options of jsonp are jsonpCallbackexport const options = { param: 'jsonpCallback' } export const ERR_OK = 0
Then encapsulate the method of obtaining the page
import jsonp from 'common/js/jsonp' import { commonParams, options } from './config' export function getRecommend() { // Get the address of qq music const url = '/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg' // () method to merge commonParams object and subsequent objects const data = ({}, commonParams, { platform: 'h5', uin: 0, needNewCode: 1 }) // The last one returned is return jsonp(url, data, options) }
Call it in the corresponding component
<script> import { getRecommend } from 'api/recommend' import { ERR_OK } from 'api/config' export default { created() { this._getRecommend() }, methods: { _getRecommend() { getRecommend().then(res => { if ( === ERR_OK) { () } }) } } } </script>
Then you can get the data in the console
Summarize
The above is what the editor introduces to you using Promise to encapsulate jsonp and retrieve data. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!