【TS】promise代替回调函数使用

参考:

https://blog.csdn.net/a42626423/article/details/135101768

https://blog.csdn.net/a42626423/article/details/135101768

typescript 复制代码
    fun() {
        return new Promise((resolve, reject) => {
            let succ = Math.random() > 0.5
            setTimeout(() => {
                if (succ) {
                    resolve(null)
                }
                else {
                    reject(null)
                }
            }, 2000)
        });
    }


    test() {
        this.fun().then((data) => {
            //成功处理resolve
        }, (data) => {
            //失败处理reject
        })
        //或者

        this.fun().then((data) => {
            //成功处理
        }).catch((error: Error) => {
            //失败处理
        })
    }
    
    //加载多个
    fun2() {
        let loadArr = []
        return new Promise((resolve, reject) => {
            Promise.all(loadArr).then(() => {
                //loadArr都执行完之后
                resolve(null);
            }).catch((error: Error) => {
                //loadArr出错
                resolve(null);
            })
        });
    }

    //链式调用
    test2() {
        let p = new Promise(resolve => {
            setTimeout(() => {
                resolve("success 1")
            }, 2000)
        })

        p.then((info) => {
            // 此处继续返回一个promise对象,形成链式调用
            return new Promise(resolve => {
                console.log("info = ", info)
                setTimeout(() => {
                    resolve("success 2")
                }, 2000)
            })
        }).then((info) => {
            console.log("info = ", info)
        }).catch((error: Error) => {
            //失败处理
        })
    }
相关推荐
浪遏5 小时前
07|网页上看着正常,导出的 PDF 为什么还会变样
typescript
浪遏5 小时前
03|自动保存真正难的部分,是保存期间又发生了修改
typescript
浪遏5 小时前
04|同一篇资料,怎样同时交给编辑器、搜索和 AI
typescript
浪遏5 小时前
09|让 Mermaid 和 HTML 成为可编辑内容块
typescript
️公子9 小时前
可插拔 13 款实时棋牌对战平台实践:房间容器、Plugin SDK 与幂等账本
websocket·typescript·游戏开发·monorepo·插件架构·棋牌平台·实时对战
FungLeo10 小时前
成为全栈·Vue 管理后台篇·Vue3 + Vite + Naive UI:后台工程基座怎么搭
前端·vue.js·ui·typescript·vite·前端工程化·biome
FungLeo10 小时前
成为全栈·Vue管理后台篇·<scriptsetup>:把页面拆成可读、可测的 Vue 组件
前端·javascript·vue.js·typescript·前端组件化·composition api·vue sfc
theMuseCatcher3 天前
Vue3导航菜单(Menu)
typescript·vue3·less
theMuseCatcher4 天前
Vue3评论(Comment)
typescript·vue3
afumu4 天前
把五个网页版 AI 拉进同一个群聊:不用 API key 的多 Agent 编排
人工智能·chrome·typescript