这是我参与「第五届青训营 」伴学笔记创作活动的第 2 天
异步处理:
方法一:在没有出现promise之前,我们使用setTimeout来处理异步
setTimeout(()=>{
var res = "fun1"
console.log("获取到f1")
callback(res)
},1000)
}
function fun2(value){
console.log(value)
}
fun1(fun2)
1 2 3 4 5 6 7 8 9 10 11 12
使用promise后
const promise = new Promise(function(resolve,reject){
console.log('promise');
resolve()
})
promise.then(function(){
console.log('resolve');
})
console.log('hi');
1 2 3 4 5 6 7 8 9
方法三:async/await
这个代码是属于同步的
await fun()
console.log(2);
}
fun1()
function fun(){
console.log(1);
}
console.log(3);
1 2 3 4 5 6 7 8 9
Promise,给予调用者一个承诺,过一会返回数据给你,就可以创建一个promise对象。 当我们new一个promise,此时我们需要传递一个回调函数,这个函数为立即执行的,称之为(executor) 这个回调函数,我们需要传入两个参数回调函数,reslove,reject(函数可以进行传参) 当执行了resolve函数,会调用promise对象的.then函数 当执行了reject函数,会回调promise对象的.catche函数
return new Promise((resolve,reject)=>{
setTimeout(()=>{
if(url === 'iceweb.io'){
resolve('我成功了,把获取到的数据传出去')
}else{
reject('url错误,请求失败')
}
},3000)
})
}
requestData('iceweb.io').then(res=>{
console.log(res);
})
requestData('iceweb.org').then(res => {},rej=>console.log(rej))
requestData('iceweb.org').catch(e=>console.log(e));
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
在函数中,new这个类的时候,传入的回调函数称之为executor(会被Promise类中自动执行)
在正确的时候调用resolve函数,失败的时候调用reject函数,把需要的参数传递出去。 异常处理
其中在.then方法中可以传入两个回调
第一个则是fulfilled的回调
第二个则是rejected的回调
回调地狱:
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url.includes('iceweb')) {
resolve(url)
} else {
reject('请求错误')
}
}, 1000);
})
}
async function getData() {
const res1 = await requestData('iceweb.io')
const res2 = await requestData(`iceweb.org ${res1}`)
const res3 = await requestData(`iceweb.com ${res2}`)
console.log(res3)
}
getData()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
async/await剖析
async(异步的)
async用于申明一个异步函数
*async内部代码同步执行
1)异步函数的内部代码执行过程和普通的函数是一致的,默认情况下也是会被同步执行
console.log('hi ice');
}
sayHi()
1 2 3 4 ** 2)异步函数的返回值**
异步函数的返回值和普通返回值有所区别
普通函数主动返回什么就返回什么,不返回为undefined
异步函数的返回值特点
明确有返回一个普通纸,相当于Promise.resolve(返回值)
返回一个thenble对象则由then方法中的resolve,或者reject有关
明确返回一个promise,则由这个promise决定
异步函数中可以使用await关键字,现在在全局也可以进行await,但是不推荐。会阻塞主进程的代码执行。
3)异步函数的异常处理
如果函数内部中途发生错误,可以通过try catch的方式捕获异常
如果函数内部中途发生错误,也可以通过函数的返回值.catch进行捕获
async function sayHi() {
console.log(res)
}
sayHi().catch(e => console.log(e))
//或者
async function sayHi() {
try {
console.log(res)
}catch(e) {
console.log(e)
}
}
sayHi()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 4)await关键字 异步函数中可以使用await关键字,普通函数不行
await特点
通常await关键字后面都是跟一个Promise
可以是普通值
可以是thenble
可以是Promise主动调用resolve或者reject
这个promise状态变为fulfilled才会执行await后续的代码,所以await后面的代码,相当于包括在.then方法的回调中,如果状态变为rejected,你则需要在函数内部try catch,或者进行.catch操作。
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url.includes('iceweb')) {
resolve(url)
} else {
reject('请求错误')
}
}, 1000);
})
}
async function getData() {
const res = await requestData('iceweb.io')
console.log(res)
}
getData()