JS中的 Promise async await

Promise是什么?

Promise是一个解决回调地狱的方案

什么是回调地狱

函数嵌套,导致可读性差,举个简单的🌰

var sayhello = function (text, callback) {
    setTimeout(function () {
        console.log(new Date().getTime(), text);
        callback();
    }, 1000);
}
sayhello("1.hello", function () {
    sayhello("2.hello", function () {
        sayhello("3.hello", function () {
            setTimeout(function () {
                console.log(new Date().getTime(), "4.goodbye");
            }, 1000);
        });
    });
});

image.png

示例

Promise

举个简单的🌰

console.log('start')
new Promise((resolve,reject)=>{
    setTimeout(()=>{
        console.log('ok')
        resolve(1)
    },1000)
}).then(res=>console.info('resolve: ',res))
console.log('end')

image.png

根据上面的demo,可以看到promise相当于启动了一个线程,并没有阻塞,继续执行下面的console.log('end'),想要获取Promise中结果,可以使用.then方法

同步和异步

在使用Promise之前async和await应该并不陌生了,举个简单的🌰

function a(){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            console.log(new Date().getTime())
            resolve(1)
        },1000)
    })
}
async function b(){
    console.log("res->",await a());
    console.log("res->",await a());
    console.log("res->",await a());
    console.log("res->",await a());
    console.log("res->",await a());
}
b()

以上示例可以看出来,await的结果就是resolve的值,原本setTimeout和Promise并不会阻塞代码运行,但是在这里就被await阻塞了

评论 0

还没有评论,来说点什么吧。

提交后需要审核才会公开。