1 知识总结:
(1)js中的异步操作:定时器、数据库操作,fs文件操作,AJAX
(2)Promise 是 js 中进行异步编程的新解决方案
(3)promise是一个构造函数,promise对象用来封装一个异步操作,并且可以获得成功或失败的返回值
(4)promise的作用:支持链式调用,解决回调地狱问题
(5) promise写法
//这里resolve和reject都是函数
const p=new Promise((resolve,reject)=>{
if(成功){
resolve(n)
}else{
reject(n)
}
})
p.then((value)=>{
//成功的操作
},(reson)=>{
//失败的操作
})
2 三个例子:
1 抽奖,100以内,如果小于等于30成功,大于30则失败。
//生成随机数
function rand(m, n) {
return Math.ceil(Math.random() * (n - m + 1)) + m - 1;
}
var btn = document.querySelector('#btn')
btn.addEventListener('click', function() {
setTimeout(() => {
let n = rand(1, 100)
if (n <= 30) {
alert('success'+value)
console.log(n);
} else {
alert('fail'+value)
}
}, 5000)
})
改造:
//resolve 函数
//reject 函数
const p = new Promise((resolve, reject) => {
setTimeout(() => {
let n = rand(1, 100)
if (n <= 30) { //成功调用resolve(n),并传递n
resolve(n)
} else { //失败调用reject(n),并传递n
reject(n)
}
}, 5000)
})
p.then((value) => { //成功
alert('success' + value)
}, (reson) => { //失败
alert('fail' + reson)
})
2 读取文件内容
const fs = require('fs');
fs.readFile('test.txt', (err, data) => {
if (err) throw err;//失败抛出错误
console.log(data.toString()); //成功则打印数据
})
改造后:
const p = new Promise((resolve, reject) => {
fs.readFile('test.txt', (err, data) => {
if (err) reject(err);
resolve(data)
})
})
p.then((value) => {
console.log(value.toString());
}, (reason) => {
console.log(reason);
})
3.ajax
一个开源的api:https://api.apiopen.top/api.html
const btn = document.querySelector('#btn');
btn.addEventListener('click', function(){
//创建 Promise
const p = new Promise((resolve, reject) => {
//1.创建对象
const xhr = new XMLHttpRequest();
//2. 初始化
xhr.open('GET', 'http://poetry.apiopen.top/sentences');
//3. 发送
xhr.send();
//4. 处理响应结果
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){//ajax请求完成
//判断响应状态码 2xx
if(xhr.status >= 200 && xhr.status < 300){
//控制台输出响应体
resolve(xhr.response);
}else{
//控制台输出响应状态码
reject(xhr.status);
}
}
}
});
//调用then方法
p.then(value=>{
console.log(value);
}, reason=>{
console.warn(reason);
});
});