promise:是es6的新语法,用来解决回调地狱的。
口述:promise构造函数会接受一个函数作为参数,该函数中有resolve和reject两个参数分别对应着then和catch两个方法;当调用resolve的时候就会执行then方法,调用reject时救护执行catch方法。
语法:
new Promise(function(resolve, rejct){
成功就调用resolve
失败就调用reject
}).then(res => {
}).catch(res => {
})
同步和异步:new promise中的回调函数是同步代码,promise对象的then方法是异步代码
new Promise(
function (resolve) {
console.log(1);
resolve(2)
}
// 这个匿名函数中的代码是同步的
).then(res => { // then才是异步的
console.log(res);
})
console.log(3);
// 结果是 1 3 2 ,所以new Promise中的回调函数是同步代码,promise对象的then方法才是异步代码
回调地狱的终极解决方案 async:
async function fn(a, b) {
return a + b
// 调用async会先return new Promise(function(resolve){
// resolve(a + b)
// })
}
var res = fn(1, 2)
console.log(res); // 输出promise对象
res.then(res => { // 要得到原先函数中返回的结果,需要调用then方法得到
console.log(res); //输出3
})
作用:简化promise的使用(不用再使用then()来指定成功或失败的回调函数)以同步编码的方式实现异步流程(没有回调函数)。
async:async函数在调用后,会得到一个promise对象,如果要得到其中返回的值,需要调用promise对象的then方法;当函数执行的时候,一旦遇到 await 就会先返回,等到触发的异步操作完成,再接着执行函数体内后面的语句。
注意点:1.await 命令只能用在 async 函数之中,如果用在普通函数,就会报错。
2.如果async修饰的函数中没有await关键字, 跟普通函数一样,就是同步函数。