前后端交互

接口的调用方式

  • 原生ajax
  • 基于JQuery的ajax
  • Fetch
  • Promise

image.png

url的地址格式

传统的url
image.png
image.png

Restful形式的url

image.png

promise

 通过new Promise()来创建一个promise对象,promise里面的构造函数中有两个参数(resolve,reject),代表成功和失败的两种情况,并通过then来返回结果。

js常见的异步调用

  • 定时器
  • ajax
  • 事件函数

promise

promise主要是为了解决异步编程的解决方案

主要是解决异步深层嵌套 而且语法更加简洁
<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport"
 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Promise的基本使用</title>
</head>
<body>
</body>
<script>
 console.log( typeof Promise);
 console.dir(Promise)
    let p = new Promise(function (resolve,reject){
        setTimeout(function (){
             let flag = true;
             if(flag) {
                 resolve('true')
             }else {
                 reject('Error')
             }
        },2000)
    })
    p.then(function (data){
        console.log(data)
    },function (data){
        console.log(data)
    })
</script>
</html>

image.png

promise的常用API之实例方法

实例方法

  • then():得到异步任务正确的结果
  • catch():获取正常信息
  • finally():成功与否都会执行。

image.png

!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>promise的基本API</title>
</head>
<body>
</body>
<script>
 function queryData() {
        return new Promise(function (resolve, reject){
            setTimeout(function (){
                let flag = false;
                if(flag) {
                    resolve('true')
                }else {
                    reject('false')
                }
            },2000)
        })
    }
    queryData().then(function (data){
        console.log(data)
    }).catch(function (data){
        console.log(data)
    }).finally(function (){
        console.log('finally')
    })
</script>
</html>![image.png](/img/bVcKdlc)

image.png

promise之常用API之对象方法

image.png


已注销
54 声望3 粉丝

保持呼吸 坚持学习


« 上一篇
Vue组件
下一篇 »
Vue