首页 > Web开发 > 详细

node.js的Promise对象的使用

时间:2019-08-25 01:57:15      阅读:80      评论:0      收藏:0      [点我收藏+]

Promise对象是干嘛用的?

将异步操作以同步操作的流程表达出来

一、Promise对象的定义

let flag = true;
const hello = new Promise(function (resolve, reject) {
    if (false) {//异步操作成功
        resolve("success");
    } else {
        reject("error");
    }
});

二、链式调用-then方法

使用then方法调用,第一个参数是成功回调,第二个参数是失败回调,如下

hello.then(
    function (value) {
        console.log(value)
    },
    function (err) {
        console.log(err)
    }
);

下面我们分别定义三个方法,参数为延时执行的秒数

  1. chenqionghe
  2. get
  3. muslce
function chenqionghe(second) {
    return new Promise((resolve, reject) => {
        setTimeout(function () {
            console.log("chenqionghe");
            resolve();
        }, second * 1000);
    })
}
function get(second) {
    return new Promise((resolve, reject) => {
        setTimeout(function () {
            console.log("get");
            resolve()
        }, second * 1000);
    })
}

function muscle(second) {
    return new Promise((resolve, reject) => {
        setTimeout(function () {
            console.log("muscle");
            resolve();
        }, second * 1000);
    })
}

调用如下

chenqionghe(3)
    .then(function () {
        return get(2)
    })
    .then(function () {
        return muscle(1)
    });

运行输出

chenqionghe
get
muscle

这样就实现了链式的调用,相当于同步的方式执行了

如果不使用then调用,会发生什么情况?如下

chenqionghe(3);
get(2);
muscle(1);

结果如下

muscle
get
chenqionghe

我们看到chenqionghe虽然是第一个执行,却是最后输出内容,因为设置了3秒后执行

三、捕获异常-catch

chenqionghe(3)
    .then(function () {
        return get(2)
    })
    .then(function () {
        throw new Error("abc");
        return muscle(1)
    })
    .catch(function (e) {
        console.log("异常:" + e.message)
    })
;

输出

chenqionghe
get
异常:abc

异常本质也是一个Promise,所以后面还可以执行then

chenqionghe(3)
    .then(function () {
        return get(2)
    })
    .then(function () {
        throw new Error("abc");
        return muscle(1)
    })
    .catch(function (e) {
        console.log("异常:" + e.message)
    })
    .then(function () {
        console.log("异常后执行")
    })
;

运行输出

chenqionghe
get
异常:abc
异常后执行

四、收尾执行-finally

就是不管怎么样,都会执行的方法,即使是抛异常了

chenqionghe(3)
    .then(function () {
        return get(2)
    })
    .then(function () {
        throw new Error("abc");
        return muscle(1)
    })
    .catch(function (e) {
        console.log("异常:" + e.message)
    })
    .finally(function () {
        console.log("最后都会执行的方法")
    })
;

执行输出

node.js的Promise对象的使用

原文:https://www.cnblogs.com/chenqionghe/p/11406666.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!