目录

一、构建Promise

二、Promise的使用

三、Promise函数

四、常见问题

五、异步函数

实例:


Primise是es6提供的一个类,目前用于书写更优雅地异步任务。对于某些浏览器的适配并不那么好使用需要注意。

一、构建Promise

new Promise(function (resolve, reject) {
    // 要做的事情...
});

通过新建一个Promise对象好像并没有看出它怎样更优雅地书写复杂的异步任务。我们之前遇到的异步任务都是一次异步,如果需要多次调用异步数据呢?

setTimeout(function () {
    console.log("First");
    setTimeout(function () {
        console.log("Second");
        setTimeout(function () {
            console.log("Third");
        }, 3000);
    }, 4000);
}, 1000);

这段程序实现了隔一秒调用一次,但是它是用“函数瀑布”来实现的,这回让函数看起来非常的冗余。那么接下来我们换Promise来实现同样的功能:

new Promise(function (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的使用

下面我们通过剖析这段Promise计时器来讲述Promise的使用:

Promise构造函数只有一个参数,式一个函数,这个函数在构造之后会直接被异步运行,所以我们称之为起始函数。起始函数包含两个参数resolve和reject。

当Promise被构造时,其实函数会被异步执行:

new Promise(function (resolve, reject) {
    console.log("Run");
});

这段程序会直接输出Run。

resolve和reject都是函数,其中调用resolve代表一切正常,reject是出现异常时所调用的:

new Promise(function (resolve, reject) {
    var a = 0;
    var b = 1;
    if (b == 0) reject("Divide zero");
    else resolve(a / b);
}).then(function (value) {
    console.log("a / b = " + value);
}).catch(function (err) {
    console.log(err);
}).finally(function () {
    console.log("End");
});

//运行结果
a / b = 0
End

Promise类有.then() .catch() 和 .finally() 三个方法,者三个方法的参数都是一个函数,.then()可以将参数中的函数添加到当前Promise的正常执行序列,.catch()则是设定Promise的异常处理序列,.finally()是在Promise执行的最后一定会执行的序列。.then()传入的函数会按顺序依次执行,有任何异常都会直接跳到catch序列。

new Promise(function (resolve, reject) {
    console.log(1111);
    resolve(2222);
}).then(function (value) {
    console.log(value);
    return 3333;
}).then(function (value) {
    console.log(value);
    throw "An error";
}).catch(function (err) {
    console.log(err);
});

//执行结果
1111
2222
3333
An error

resolve()中可以放置一个参数用于向下一个then传递一个值,then中的函数也可以返回一个值给then。但是如果then中返回的是一个Promise对象,那么下一个then将相当于对这个饭hi的Promise进行操作,这一点从刚才的计时器的例子中可以看出。

reject()参数中一半hi传递一个异常给之后catch函数用于处理异常。

但是需要注意以下两点:

1、resolve和reject的作用域只有起始函数,不包括then以及其他序列。

2、resolve和reject并不能够使起始函数停止运行,需要return来终止。

三、Promise函数

上述的“计时器”程序看上去比函数瀑布还要长,所以我们可以将它的核心部分写成一个Promise函数:

function print(delay, message) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(message);
            resolve();
        }, delay);
    });
}
print(1000, "First").then(function () {
    return print(4000, "Second");
}).then(function () {
    print(3000, "Third");
});

这种返回值为一个Promise对象的函数称作Promise函数,它常常用于开发基于异步操作的库。

四、常见问题

Q: then、catch 和 finally 序列能否顺序颠倒?

A: 可以,效果完全一样。但不建议这样做,最好按 then-catch-finally 的顺序编写程序。

Q: 除了 then 块以外,其它两种块能否多次使用?

A: 可以,finally 与 then 一样会按顺序执行,但是 catch 块只会执行第一个,除非 catch 块里有异常。所以最好只安排一个 catch 和 finally 块。

Q: then 块如何中断?

A: then 块默认会向下顺序执行,return 是不能中断的,可以通过 throw 来跳转至 catch 实现中断。

Q: 什么时候适合用 Promise 而不是传统回调函数?

A: 当需要多次顺序执行异步操作的时候,例如,如果想通过异步方法先后检测用户名和密码,需要先异步检测用户名,然后再异步检测密码的情况下就很适合 Promise。

Q: Promise 是一种将异步转换为同步的方法吗?

A: 完全不是。Promise 只不过是一种更良好的编程风格。

Q: 什么时候我们需要再写一个 then 而不是在当前的 then 接着编程?

A: 当你又需要调用一个异步任务的时候。

五、异步函数

异步函数(async function)是ECMAScript 2017(ECMA-262)标准的规范,几乎被所有浏览器锁支持除了IE。。。

在 Promise 中我们编写过一个 Promise 函数:

function print(delay, message) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(message);
            resolve();
        }, delay);
    });
}

然后用不同的事件间隔输出了三行文本:

print(1000, "First").then(function () {
    return print(4000, "Second");
}).then(function () {
    print(3000, "Third");
});

我们可以将这段代码变得更好看:

async function asyncFunc() {
    await print(1000, "First");
    await print(4000, "Second");
    await print(3000, "Third");
}
asyncFunc();

异步函数async function中可以使用await命令,await命令后必须跟着一个Promise,异步韩式会在这个Promise运行中暂停,直到其运行结束再继续运行。

异步函数实际上原理与Promise原生API的机制是一样的,只不过更便于程序员阅读。

处理异常的机制将用try-catch块实现:

async function asyncFunc() {
    try {
        await new Promise(function (resolve, reject) {
            throw "Some error"; // 或者 reject("Some error")
        });
    } catch (err) {
        console.log(err);
        // 会输出 Some error
    }
}
asyncFunc();

如果 Promise 有一个正常的返回值,await 语句也会返回它:

async function asyncFunc() {
    let value = await new Promise(
        function (resolve, reject) {
            resolve("Return value");
        }
    );
    console.log(value);
}
asyncFunc();

实例:

Promise在nuxt中的实际应用:
 

await Promise.all([
      $axios(getPageByCode(aboutCode)),
      $axios(getPageByCode(sponsorCode)),
      // $axios(getForumList()),
    ]).then((res) => {
      if (res && res[0] && res[0].data) {
        result.aboutContent = res[0].data.data && res[0].data.data.content;
      }
      if (res && res[1] && res[1].data) {
        result.sponsorContent = res[1].data.data && res[1].data.data.content;
      }
    });

如上为nuxt框架下单页应用中多异步接口的调用写法。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐