赞
踩
抽象表达:
Promise 是一门新的技术(ES6 规范)
Promise 是 JS 中进行异步编程的新解决方案
fs 文件操作
require('fs').readFile('./index.html', (err,data)=>{})
- 1
数据库操作
AJAX
$.get('/server', (data)=>{})
- 1
定时器
setTimeout(()=>{}, 2000);
- 1
备注:旧方案是单纯使用回调函数
具体表达:
从语法上来说: Promise 是一个构造函数
从功能上来说: promise 对象用来封装一个异步操作并可以获取其成功/ 失败的结果
实例对象中的一个属性 『PromiseState』
pending 未决定的
resolved / fullfilled 成功
rejected 失败
pending 变为 resolved/fullfilled
pending 变为 rejected
说明:
如何改变 promise 的状态
resolve(value)
: 如果当前是 pending 就会变为 resolvedreject(reason)
: 如果当前是 pending 就会变为 rejected
实例对象中的另一个属性 『PromiseResult』
保存着异步任务『成功/失败』的结果
什么是回调地狱?
回调函数嵌套调用, 外部回调函数异步执行的结果是嵌套的回调执行的条件
回调地狱的缺点
解决方案
终极解决方案
// 1) 创建 promise 对象(pending 状态), 指定执行器函数
const p = new Promise((resolve, reject) => {
// 2) 在执行器函数中启动异步任务
setTimeout(() => {
const time = Date.now()
// 3) 根据结果做不同处理
// 3.1) 如果成功了, 调用 resolve(), 指定成功的 value, 变为 resolved 状态
if (time % 2 === 1) {
resolve('成功的值 ' + time)
} else { // 3.2) 如果失败了, 调用 reject(), 指定失败的 reason, 变为rejected 状态
reject('失败的值' + time)
}
}, 2000)
})
// 4) 能 promise 指定成功或失败的回调函数来获取成功的 vlaue 或失败的 reason
p.then(
value => { // 成功的回调函数 onResolved, 得到成功的 vlaue
console.log('成功的 value: ', value)
},
reason => { // 失败的回调函数 onRejected, 得到失败的 reason
console.log('失败的 reason: ', reason)
}
)
/*
可复用的发 ajax 请求的函数: xhr + promise
*/
function promiseAjax(url) {
return new Promise((resolve, reject) => {
// 1. 创建xhr对象
const xhr = new XMLHttpRequest();
// 2. 初始化
xhr.open('GET', url);
// 3. 发送
xhr.send()
// 4. 绑定事件,处理响应结果
xhr.onreadystatechange = function () {
// 判断
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// 控制台输出响应体
resolve(xhr.response)
} else {
reject(xhr.status)
}
}
}
})
}
promiseAjax('https://api.apiopen.top/api/sentences')
.then(
data => {
console.log('显示成功数据', data)
},
error => {
alert(error.message)
}
)
Promise (excutor) {}
executor
函数: 执行器 (resolve, reject) => {}
resolve
函数: 内部定义成功时我们调用的函数 value => {}
reject
函数: 内部定义失败时我们调用的函数 reason => {}
说明: executor 会在 Promise 内部立即同步调用,异步操作在执行器中执行
Promise的同步与异步问题:
new Promise((resolve, reject) => {
console.log("resolve before");
resolve("success")
}).then(res => console.log(res))
console.log("同步");
// resolve before
// 同步
// success
(onResolved, onRejected) => {}
onResolved
函数: 成功的回调函数 (value) => {}
onRejected
函数: 失败的回调函数 (reason) => {}
(onRejected) => {}
在 promise 被拒绝时调用的函数
onRejected
函数: 失败的回调函数 (reason) => {}
then(undefined, onRejected)
(value) => {}
(reason) => {}
(promises) => {}
此方法在集合多个
promise
的返回结果时很有用。
一旦迭代器中的某个 promise 解决或拒绝,返回的 promise 就会解决或拒绝。
当 promise 改变为对应状态时都会调用
let p = new Promise((resolve, reject) => {
resolve('ok')
})
// 指定回调1
p.then(value => {
console.log(value)
})
// 指定回调2
p.then(value => {
console.log(value + 1)
})
// ok
// ok1
let p = new Promise((resolve, reject) => {
// 这里同步先改变状态,再执行.then并指定回调且执行
// resolve('ok')
// 这里异步,先执行.then并指定回调,then的回调是对应时机执行
setTimeout(() => {
resolve('ok')
}, 1000);
})
p.then(
value => {
console.log(value)
},
reason => {
console.log(reason)
}
)
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ok')
}, 1000);
})
p.then(value => {
return new Promise((resolve, reject) => {
resolve('success')
// reject('err')
})
}).then(value => {
console.log(value)
return 123
}).then(value => {
console.log(value)
throw 'err'
}).then(() => {}, reason => {
console.log(reason)
})
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ok')
}, 100);
})
p.then(value => {
// 中断Promise链条有且仅有一个方式:返回一个pending状态的Promise对象
console.log(111)
}).then(value => {
return new Promise(() => {})
console.log(222)
}).then(value => {
console.log(333)
}).catch(reason => {
console.warn(reason)
})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。