前后端交互
接口的调用方式
- 原生ajax
- 基于JQuery的ajax
- Fetch
- Promise
url的地址格式
传统的url
Restful形式的url
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>
promise的常用API之实例方法
实例方法
- then():得到异步任务正确的结果
- catch():获取正常信息
- finally():成功与否都会执行。
!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>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。