5-1创建Promise对象

promise函数中传递两个参数
resolve —>处理成功 then去触发resolve
reject —>处理失败 catch去触发reject

  1. //创建Promise对象
  2. promise函数中传递两个参数
  3. resolve -->处理成功
  4. reject -->处理失败
  5. const p=new Promise(function(resolve,reject){
  6. //成功
  7. // let data="成功了"
  8. // resolve(data);
  9. //失败
  10. let data="失败了"
  11. reject(data)
  12. })
  13. //调用Promise then方法
  14. p.then(fuction(value){
  15. console.log(value)
  16. },functiom(reason){
  17. console.log(reson)
  18. })

5-2封装ajax

  1. function http(url){
  2. return new Promise((resolve,reject)=>{
  3. $.ajax({
  4. url,
  5. success:res=>{
  6. resolve(res)
  7. },
  8. error:err=>{
  9. reject(err)
  10. }
  11. })
  12. })
  13. }
  1. var url=`http://47.108.197.28:3000/top/playlist`;
  2. http(url).then(function(res){
  3. console.log(res);
  4. })

5-3封装http

  1. var baseUrl='http://47.108.197.28:3000'
  2. function http(url){
  3. return new Promise((resolve,reject)=>{
  4. wx-wx.request({
  5. url:baseUrl+url,
  6. success: res => {
  7. resolve(res)
  8. },
  9. fail: (err) => {
  10. reject(err)
  11. },
  12. })
  13. })
  14. }
  15. function getMvHttp(){
  16. return http("/mv/first")
  17. }
  18. function getMvDetailHttp(id){
  19. return http(`mv/url?id=${id}`)
  20. }
  21. module.exports={
  22. getMvHttp,
  23. getMvDetailHttp
  24. }