promise(二)
【本文测试接口根路径:https://jsonplaceholder.typicode.com】
在es6之前,我们处理异步时常常会用回调的方式,这难免会导致回调地狱。
下面再看一个关于异步回调的案例:
而promise的出现很好地解决了这个问题,接下来我们把createPost函数加以修改:
在 promise 实例中调用resolve()方法使其状态从 pending 变为 resolved, resolve()方法中传递的参数即为then()中接收到的结果。
// 写法一:直接调用Promise的resolve方法 let promise1 = Promise.resolve(‘11111‘) promise1 .then(res => console.log(res)) // 写法二:new出一个Promise对象后调用resolve方法 let promise2 = new Promise((resolve,reject) => { resolve(‘222222‘) }) promise2 .then(res => console.log(res)) .then(()=>{console.log(‘2-2‘)}) let promise3 = new Promise((resolve,reject) => { resolve(‘3‘) }) promise3 .then(res => console.log(‘33333‘)) .then(()=>{console.log(‘3-3‘)}) // 模拟异步 let promise4 = new Promise((resolve,reject) => { setTimeout(resolve,2000,‘44444‘) }) promise4 .then(res => console.log(res)) // Promise.all()中传递一个数组,当其中所有的promise都处理完毕后才返回结果 Promise.all([promise1,promise2,promise3,promise4]) .then(res => {console.log(res)})
打印结果如下:
fetch
fetch请求返回一个 promise 对象:
let resData = fetch(‘https://jsonplaceholder.typicode.com/users‘) let promise = Promise.resolve(resData).then(res => res.json()).then(data => console.log(data))
但是这样每次请求完数据都需要调用 resolve() 方法并转为 json 格式,比较麻烦,
下面我们封装 fetch 请求:
// 写法一:class TestHttp { get(url) { return new Promise((resolve,reject) => { fetch(url) .then(res => res.json()) .then(res => resolve(res)) .catch(err => reject(new Error("报错了"))) }) } } const $http = new TestHttp() $http.get(‘https://jsonplaceholder.typicode.com/users‘) .then(res => console.log(res)) .catch(err => console.log(err)) // 写法二: class TestHttp1 { get(url) { return fetch(url) .then(res => res.json()) .then(res => console.log(res)) .catch(err => console.log(err)) } } const $http1 = new TestHttp1() var result = $http1.get(‘https://jsonplaceholder.typicode.com/users‘)
接下来我们用 async await 的方式进行封装:
class TestHttp { async get(url) { const response = await fetch(url) let flag = false if (!flag) { const resData = await response.json() return resData } else { await Promise.reject(new Error("error:报错了")) } } } const $http = new TestHttp() $http.get(‘https://jsonplaceholder.typicode.com/users‘) .then(res => console.log(res)) .catch(err => console.log(err))
async await
// 写法一: let promise = new Promise((resolve,reject) => { setTimeout(()=> { let obj = {name:‘zhangsan‘,age:22} resolve(obj) },2000) }) promise .then(res => console.log(res)) // 写法二: async function testFn() { let getData = await new Promise((resolve,reject) => { setTimeout(()=> { let obj = {name:‘zhangsan‘,age:32} resolve(obj) },2000) }); let result = await getData return result } testFn().then(res => {console.log(res)})
相关推荐
88520191 2020-06-13
Magicsoftware 2020-05-26
nmgxzm00 2020-11-10
xixixi 2020-11-11
88254251 2020-11-01
MarukoMa 2020-09-02
88234852 2020-09-15
陈旭阳 2020-08-31
whynotgonow 2020-08-19
前端开发Kingcean 2020-07-30
whynotgonow 2020-07-29
bowean 2020-07-08
前端开发Kingcean 2020-07-08
88520191 2020-07-05
前端开发Kingcean 2020-06-27
88481456 2020-06-18
whynotgonow 2020-06-16
88520191 2020-06-13