美文网首页让前端飞
Promise的一些实践

Promise的一些实践

作者: LOWINC | 来源:发表于2017-05-10 23:02 被阅读0次

业务中出现的小bug,趁此机会总结一下对Promise的实践经验。

  • 链式发起,逐个回调
  • 同步发起,按返回时间回调
  • 同步发起,全部执行完在进行回调
  • more...

主要用到以下特性

promise


原始地址

详细内容 地址
作者 MaBond


1. 模拟的ajax请求

模拟服务器处理

     const server = function (url, num) {
        console.log(`servering in ${num}`)
        return new Promise(function (res, rej) {
            setTimeout(function () {
                /* 
                    注意
                        只要有返回都视为成功的一次请求
                        只有 没填写url,或者get post写反才是失败

                    注意
                    reslove()
                    console.log('xxxxx') //  xxxx  在resolve之后的代码还是会执行  => 写出 return reslove()

                */
                if (!url) {
                    return rej('404')
                }
                if (num > 10) {
                    return res({
                        success: true,
                        num: num,
                        data: [
                            {
                                name: 'sunweiqi',
                                age: 100
                            },
                            {
                                name: 'qiqiqi',
                                age: 18
                            }
                        ]
                    })
                } else {
                    return res({
                        success: false,
                        num: num,
                        msg: '粗错了: num < 10'
                    })
                }

            }, Math.random() * 3000)
        })
    }

模拟fetch

    const fetch = async function (url, num) {
        try {
            let response = await server(url, num)
            return Promise.resolve(response)
        } catch (error) {
            return Promise.reject(error)
        }

    }

封装fetch

    const getData = async (url, num) => {
        try {
            const result = await fetch(url, num)
            return Promise.resolve(result)
        } catch (error) {
            throw new Error(error)
        }
    }

2. 几种不同的请求执行方式

2.1 依次逐个发起 完成后 在进行下一个请求

    const getByOrder = async () => {
        try {

            const res_1 = await getData('url_1', 111)
            if (res_1.success) {
                console.log("res_1 成功!=> ", res_1.data)
            } else {
                console.log("res_1 失败! => ", res_1.msg)
            }

        } catch (error) {
            console.error(error)
        }

        try {
            const res_2 = await getData('', 222)
            if (res_2.success) {
                console.log("res_2 成功!=> ", res_2.data)
            } else {
                console.log("res_2 失败! => ", res_2.msg)
            }
        } catch (error) {
            console.error(error)
        }

        try {
            const res_3 = await getData('url_3', 1)
            if (res_3.success) {
                console.log("res_3 成功!=> ", res_3.data)
            } else {
                console.log("res_3 失败! => ", res_3.msg)
            }
        } catch (error) {
            console.error(error)
        }
    }

    getByOrder()

控制台输出结果

        servering in 111
        res_1 成功!=> (2)[{ … }, { … }]

        servering in 222
        Error: 404
            at getData 
            at <anonymous>
            
        servering in 1
        res_3 失败! => 粗错了: num < 10

程序按照请求顺序链式发生,且等到上一步执行完毕才继续执行下一步

2.2 同步发起,按返回时间回调

    getData('url_1', 111).then(res => {
        if (res.success) {
            console.log("url_1 成功!=> ", res.data)
        } else {
            console.log("url_1 失败! => ", res.msg)
        }
    }).catch(error => console.error(error))

    getData('', 222).then(res => {
        if (res.success) {
            console.log("url_2 成功!=> ", res.data)
        } else {
            console.log("url_2 失败! => ", res.msg)
        }
    }).catch(error => console.error(error))

    getData('url_3', 1).then(res => {
        if (res.success) {
            console.log("res_3 成功!=> ", res.data)
        } else {
            console.log("res_3 失败! => ", res.msg)
        }
    }).catch(error => console.error(error))

控制台输出结果

    servering in 111
    servering in 222
    servering in 1

    Error: 404
        at getData 
        at <anonymous>

    res_3 失败! => 粗错了: num < 10
    url_1 成功!=> (2)[{ … }, { … }]
    三个请求同时发起,按照返回时间逐个回调

2.3 同步发起,全部执行完在进行回调

    const getAll = async () => {
        try {
            const [res_1, res_2, res_3] = await Promise.all([getData('url_1', 111), getData('', 222), getData('time_3', 1)])
            if (res_1.success) {
                console.log("res_1 成功!=> ", res_1.data)
            } else {
                console.log("res_1 失败! => ", res_1.msg)
            }
            if (res_2.success) {
                console.log("res_2 成功!=> ", res_2.data)
            } else {
                console.log("res_2 失败! => ", res_2.msg)
            }
            if (res_3.success) {
                console.log("res_3 成功!=> ", res_3.data)
            } else {
                console.log("res_3 失败! => ", res_3.msg)
            }
        } catch (error) {
            console.error(error)
        }
    }

    getAll()

控制台输出结果

    servering in 111
    servering in 222
    servering in 1
    Error: 404
        at getData 
        at <anonymous>

四个请求同步发起,等到最久的一个执行完后在进行回调

2.4 未完待续

相关文章

  • Promise的一些实践

    业务中出现的小bug,趁此机会总结一下对Promise的实践经验。 链式发起,逐个回调 同步发起,按返回时间回调 ...

  • promise 实践

    Promise 对象用于一个异步操作的最终完成(或失败)及其结果值的表示。简单点说,它就是用于处理异步操作的,异步...

  • ES6 Promise

    ES6 promise 的一些常用方法 Promise.prototype.then() Promise.prot...

  • Promise

    你会收获 为什么需要promise promise的基础用法 底层实现 最佳实践 未来发展 项目准备 注:下面说到...

  • Promise对象

    Promise 多个异步回调: 详情关于promise对象的一些讲解 Promise.all() .catch()用法

  • Promise

    前言 回过头来整理下Promise Promise Promise的一些基本点3个state:pendingful...

  • promise新手常见问题

    导读 上周讲了promise用法,这周我们讲一下promise实战中可能出现得一些易错点,如果对promise基础...

  • ES6 的 Promise实践

    Promise是对未来的预测,是异步编程的一种解决方案,ES6将其写进了语言标准,统一了...

  • Promise 的不完全试坑记录

    Promise 主要就是记忆一下关于 Promise 的一些不太好理解的问题 当在 resolve 或者 reje...

  • 登录之promise

    一、思考: 为什么要把一些方法写到vuex里面1.写到vuex里面,会使用promise,在promise里面就会...

网友评论

    本文标题:Promise的一些实践

    本文链接:https://www.haomeiwen.com/subject/cxhntxtx.html