Promise、Async、Await

promise

概念:Promise 对象用于表示一个异步操作的最终完成 (或失败)及其结果值。

新建一个promise对象

new Promisefunction(req,res){
	//要做的事情
})

实例:分三次输出字符串,第一次间隔1秒,第二次间隔4秒,第三次间隔3秒

//普通实现效果
setTimeout(function(){
	console.log("First")
	setTimeout(function(){
		console.log("Second")
		setTimeout(function(){
		console.log("Third")
		},3000)
	},4000),1000//用promise实现同样的功能
new Promisefunction(resolve,reject){
	setTimeout(function(){
		console.log("First")
		resolve(),1000)
}).then(function(){
	return new Promise(function(resolve,reject){
		setTimeout(function(){
		console.log("Second")
		resolve()
		},4000)
	})
}).then(function(){
setTimeout(function(){
	console.log("Third")
},3000)

})

注意:

  • Promise构造函数只有一个参数,是一个函数,这个函数在构造之后就直接被异步运行,所以我们称之为起始函数。起始函数包含两个参数resolve和reject(当Promise被构造时,起始函数被异步执行)
  • resolve和reject都是函数,其中调用resolve代表正常,reject是出现异常时调用的
  • Promise类有.then .catch 和finally()三个方法,这三个方法的函数都是一个参数,
    .then()可以将参数中的函数添加到当前Promise的正常执行序列
    .catch()设定Promise的异常处理序列
    .finally()是Promise执行的最后一定会执行的序列
    (then()传入的函数会按顺序依次执行,有任何异常会直接调到catch序列)
  • resolve 和 reject 的作用域只有起始函数,不包括 then 以及其他序列;
  • resolve 和 reject 并不能够使起始函数停止运行,别忘了 return。

Async和Await

概念:async是es7才有的与异步操作有关的关键字,和Promise,Generator有很大关系

  • async函数返回一个Promise对象,可以使用then方法添加回调函数
async function a(){
        return "hellow"
}
console.log(a())    //Promise { 'hellow' }

a().then (v => {
    console.log(v); 
})  //hellow
  • async函数中可能会有await表达式,async函数在执行时,如果与遇到await就会暂停执行,等触发的异步操作完成后,恢复async函数的执行并返回解析值
  • await关键字仅在async function中有效。如果在async function函数体外使用await,会得到一个语法错误
function testAwait(){
   return new Promise((resolve) => {
       setTimeout(function(){
          console.log("testAwait");
          resolve();
       }, 1000);
   });
}
 
async function helloAsync(){
   await testAwait();
   console.log("helloAsync");
 }
helloAsync();
// testAwait
// helloAsync
  • 正常情况下,await命令后面是一个Promise对象,它也可以跟其他值,如字符串,布尔值,数值以及普通函数
  • await针对所跟不同表达式的处理方式:
    • Promise对象:await会暂停执行,等待Promise对象resolve,然后恢复async函数的执行返回解析值
    • 非Promise对象:直接返回对应的值*
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值