Promise的用法以及作用

一、介紹

??Promise是一種常用的異步解決方案,解決回調(diào)地獄的問題。
??Promise可以解決兩個問題:

  • 對象的狀態(tài)不受外界影響。
  • 一旦狀態(tài)改變,就不會再變,任何時候都可以得到這個結(jié)果。

??Promise發(fā)送的請求會經(jīng)歷三個過程:padding(進行中)、fullfilled(成功)、rejected(失敗)。當狀態(tài)決定后就不會在改變,這個時候就會把狀態(tài)改為resolved(已定型)

二、使用

??我通常配合vue和axios進行使用。

首先封裝axios

import axios from 'axios'
//設(shè)置超時時間
axios.defaults.timeout = 10000

//設(shè)置請求頭
axios.defaults.headers.post['Content-Type']='multipart/form-data; boundary=<calculated when request is sent>'

//請求攔截
axios.interceptors.request.use(
    config => {
        return config
    },
    error => {
        return Promise.error(error)
    }
)

// 響應(yīng)攔截器
// axios.interceptors.response.use(
//     response => {
//         // 如果返回狀態(tài)碼200 說明接口請求成功
//         console.log(response)
//     }
// )

// get方法 對應(yīng)get請求
// url 請求地址
// params 請求時攜帶的參數(shù)

export function get(url , params){
    return new Promise((resolve , reject) => {
        axios.get(url,{
            params
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}


// post方法 對應(yīng)post請求

export function post(url,params){
    return new Promise((resolve,reject)=>{
        axios.post(url,params).then(res=>{
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}

// export function request(state,url,params){
//     if(state == "get"){
//         return this.get(url,params)
//     }else if(state == "post"){
//         return this.post(url,params)
//     }else{
//         return 'error'
//     }
// }

然后封裝接口

// 暴露接口
import {post} from './http'

// 登錄接口
export let sysLogin = (sysuser) => {
    let params = new URLSearchParams()
    params.append('username',sysuser.username)
    params.append('password',sysuser.password)
    return post('/customer/sysLogin',params)
}

// 初始化接口
export let initSystem = () =>{
    return post("/customer/initSystemuser",{})
}

在組件中調(diào)用

methods:{
        takelogin(){
            let sysuser = new Object()
            sysuser.username = this.username
            sysuser.password = this.password
            // let res = sysLogin(sysuser)
            sysLogin(sysuser).then(
                res=>{
                    console.log(res)
                    console.log(typeof res.message)
                    console.log(res.message)
                    if(res.message){
                        this.$message({
                            message: '登錄成功',
                            type: 'success'
                        });
                        this.$router.push("/page")
                    }else{
                        this.$message({
                            message: '登錄失敗',
                            type: 'error'
                        });
                    }
                }
            )
            
        },
        initSystem(){
            initSystem().then(
                res=>{
                    if(res.message){
                         this.$message({
                            message: '初始化成功',
                            type: 'success'
                        });
                    }else{
                        this.$message({
                            message: '初始化失敗或您已經(jīng)初始化',
                            type: 'error'
                        });
                    }
                }
            )
        }
    },

三、Promise的函數(shù)

Promise有以下函數(shù):

let p = new Promise
[1] p.prototype.then()
[2] p.prototype.catch()
[3] p.prototype.finally()
[4] p.all()
[5] p.race()
[6] p.allSettled()
[7] p.any()
[8] p.resolve()
[9] p.reject()
[10] p.try()

[1] p.prototype.then()

then方法是定義在原型對象Promise.prototype上的。
它的作用是為 Promise 實例添加狀態(tài)改變時的回調(diào)函數(shù)。
then方法的第一個參數(shù)是resolve,第二個是rejected

[2] p.prototype.catch()

catch方法是一個then方法的一個別名,是then(null,rejected)這樣的一個狀態(tài)。

[3] p.prototype.finally()

finally是用于指定不管 Promise 對象最后狀態(tài)如何,都會執(zhí)行的操作。
finally方法的回調(diào)函數(shù)不接受任何參數(shù),導(dǎo)致前面的 Promise 狀態(tài)到底是fulfilled還是rejected,所以finally方法里面的操作不依賴于 Promise 的執(zhí)行結(jié)果。
不使用finally方法,同樣的語句需要為成功和失敗兩種情況各寫一次。有了finally方法,則只需要寫一次。

[4] p.all()

Promise.all()方法用于將多個 Promise 實例,包裝成一個新的 Promise 實例
.all()方法的參數(shù)是一個Promise數(shù)組
當多種Promise的狀態(tài)不一致時會出現(xiàn)兩種現(xiàn)象
    ·狀態(tài)都變成fulfilled,p的狀態(tài)才會變成fulfilled,此刻返回值會變成一個數(shù)組返回給p
    ·多個Promise里存在一個rejected則會導(dǎo)致整體狀態(tài)成為Promise,并且返回第一個rejected的詳細信息。

[5]p.race()

Promise.race()方法同樣是將多個 Promise 實例,包裝成一個新的 Promise 實例。

[6] p.allSettled()

Promise.allSettled()方法接受一組 Promise 實例作為參數(shù),包裝成一個新的 Promise 實例。只有等到所有這些參數(shù)實例都返回結(jié)果,不管是fulfilled還是rejected,

[7] p.any()

該方法接受一組 Promise 實例作為參數(shù),包裝成一個新的 Promise 實例返回。
只要參數(shù)實例有一個變成fulfilled狀態(tài),包裝實例就會變成fulfilled狀態(tài);
如果所有參數(shù)實例都變成rejected狀態(tài),包裝實例就會變成rejected狀態(tài)。

[8]p.resolve()

有時需要將現(xiàn)有對象轉(zhuǎn)為 Promise 對象,Promise.resolve()方法就起到這個作用。

[9]p.reject()

Promise.reject(reason)方法也會返回一個新的 Promise 實例,該實例的狀態(tài)為rejected。

[10]p.try()

實際開發(fā)中,經(jīng)常遇到一種情況:不知道或者不想?yún)^(qū)分,函數(shù)f是同步函數(shù)還是異步操作,但是想用 Promise 來處理它。
因為這樣就可以不管f是否包含異步操作,都用then方法指定下一步流程,用catch方法處理f拋出的錯誤。

通常"Promise.resolve().then(f) "用這種方式把f變成符合promise的函數(shù),但是如果f是同步函數(shù)這就會導(dǎo)致f只會在本段程序的末尾執(zhí)行,有兩種寫法可以解決這個問題。

??方法一:第一種寫法是用async函數(shù)來寫。

const f = () => console.log('now');
(async () => f())();
console.log('next');

??方法二:第二種寫法是使用new Promise()。

const f = () => console.log('now');
(
  () => new Promise(
    resolve => resolve(f())
  )
)();
console.log('next');

p.try()就是解決以上的執(zhí)行方式的痛點Promise.try為所有操作提供了統(tǒng)一的處理機制,所以如果想用then方法管理流程,最好都用Promise.try包裝一下。這樣有許多好處,其中一點就是可以更好地管理異常。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容