ES8:async await 更加优雅的异步编程解决方案

async await  

  • async 和 await 是一种更加优雅的异步编程解决方案,是 Promise 扩展
  • async 让我们写起 Promise 像同步操作

async await 基本语法

  • 前面加 async 的函数,在执行后都会自动返回一个 Promise 对象
async function foo() {
    return 'es'
}
console.log(foo())

  • await 后面需要跟异步操作,否则没有意义
  • await 后面的 Promise 对象不必写 then,因为 await 的作用之一就是获取后面 Promise 对象成功状态传递出来的参数
function timeout() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(1)
            resolve()
        }, 1000)
    })
}

// 不加 async 和 await 是2、1   加了是 1、2
async function foo() {
    await timeout()
    console.log(2)
}
foo()

async await 对失败处理

  • Promise 对象成功状态 fulfilled 和失败状态 rejected 里面的 resolve() 和 reject() 返回的值,只能通过 then() 或 catch() 获取
  • async 函数中使用 await,await 后面跟的代码会变成同步任务,只有等 await 后面的 Promise 执行完成得到结果才会继续下去,await 就是等待的意思
function timeout() {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
				// resolve('success')
				reject('error')
		}, 1000)
	})
}
async function foo() {
	return await timeout()
}
foo().then(res => {
	console.log(res)
}).catch(err => {
	console.log(err) // error
})

案例:需要发送多个请求,后面请求发送总是需要依赖上一个请求返回的数据

  • 既可以用 Promise 链式调用来解决,也可以用 async/await 来解决,后者更简洁
  • await 只能在 async 标记的函数内部使用,单独使用会触发 Syntax error
// 封装 ajax 请求函数
function ajax(url, successCallback, failCallback){
	let xmlhttp
	if(window.XMLHttpRequest){
		xmlhttp = new XMLHttpRequest()
	} else {
		xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
	}

	xmlhttp.open('GET', url, true)
	xmlhttp.send()

	xmlhttp.onreadystatechange = function(){
		if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
			const obj = JSON.parse(xmlhttp.responseText)
			successCallback(obj)
		} else if(xmlhttp.readyState === 4 && xmlhttp.status === 404) {
			failCallback(xmlhttp.statusText)
		}
	}
}

// 封装 Promise 请求函数
function request(url){
	return new Promise((resolve, reject) => {
		ajax(url, res => {
			resolve(res)
		}, err => {
			resolve(err)
		})
	})
}

const url1 = 'http://jsonplaceholder.typicode.com/users'
const url2 = 'http://jsonplaceholder.typicode.com/todos'
const url3 = 'http://jsonplaceholder.typicode.com/photos1'

// 使用 async await 发送请求
async function getData(){
	const res1 = await request(url1)
	console.log(res1)
	const res2 = await request(url2)
	console.log(res2)
	const res3 = await request(url3)
	console.log(res3)
}
getData()

Promise 对象_taoqidejingling的博客-CSDN博客Promise Ajax 请求函数封装;Promise 优势;Promise 内部状态;Promise 原型链方法;Promise 静态方法6个;https://blog.csdn.net/taoqidejingling/article/details/122990974

异步操作前置知识_taoqidejingling的博客-CSDN博客JS 是单线程语言;同步任务和异步任务;Ajax 请求;Callback Hell 回调地狱(回调深渊)https://blog.csdn.net/taoqidejingling/article/details/122984154

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值