一、原始方法注入数据
1 // 初始化方法 2 constructor () { 3 // token 4 this.token = "Z1QljZOZiT4NTG" 5 6 // 请求地址 7 this.req_url = 'http://api.txapi.cn/v1/oil_price' 8 }
二、开始查询油价
1 // 查询油价 2 query_oil_prices (url, token) { 3 let p = new Promise(function (resolve, reject) { 4 axios({ 5 url: url, 6 method: 'GET', 7 params: { 8 token: token 9 } 10 }).then(resp => { 11 if(resp.data.code !== 200){ 12 console.log("查询失败") 13 } else { 14 resolve(resp.data) 15 } 16 }) 17 }) 18 return p 19 }
三、封装run函数
1 // run函数 2 run () { 3 this.query_oil_prices(this.req_url, this.token).then(res => { 4 console.log(res); // 查询结果 5 }) 6 }
四、完整代码
1 const axios = require('axios') 2 3class Parse { 4 // 初始化方法 5 constructor () { 6 // token 7 this.token = "Z1QljZOZiT4NTG" 8 9 // 请求地址 10 this.req_url = 'http://api.txapi.cn/v1/oil_price' 11 } 12 13 // 查询油价 14 query_oil_prices (url, token) { 15 let p = new Promise(function (resolve, reject) { 16 axios({ 17 url: url, 18 method: 'GET', 19 params: { 20 token: token 21 } 22 }).then(resp => { 23 if(resp.data.code !== 200){ 24 console.log("查询失败") 25 } else { 26 resolve(resp.data) 27 } 28 }) 29 }) 30 return p 31 } 32 33 // run函数 34 run () { 35 this.query_oil_prices(this.req_url, this.token).then(res => { 36 console.log(res); // 查询结果 37 }) 38 } 39} 40 41if(__filename === process.mainModule.filename) { 42 // new一个Parse对象 43 const p = new Parse() 44 45 // 调用run方法 46 p.run() 47}