Vue:Promise概要


1、Promise中then是異步的

2、Promise 的then里面兩個回調,默認第一個resolve,第二個reject;不會進入catch;如果只有一個回調則進入catch

 var p1=new Promise((resolve,rej) => {
        console.log('沒有resolve')
        //throw new Error('直接throw錯誤,替代reject') 或者 reject(new Error(/*Error*/));
        rej('失敗了')

 })
//then里面兩個回調,默認第一個resolve,第二個reject;不會進入catch;如果只有一個回調則進入catch
 p1.then(data =>{
    console.log('data::',data);
 },err=> {
    console.log('err::',err)
 }).catch(
    res => {
    console.log('catch data::', res)
 })
//輸出:
//沒有resolve
//err:: 失敗了

 

3、鏈式傳值

/*例1.使用Promise.resolve()啟動*/
let task1 = (value1)=>value1+1;
let task2 = (value2)=>value2+2;
let task3 = (value3)=>{console.log(value3+3)};

Promise.resolve(1).then(task1).then(task2).then(task3);//console => 7

//如果需要resolve()往后傳遞多個參數,不能直接寫resolve(a1,a2,a3),這樣只能拿到第一個要傳的參數,需要以數組或對象去傳遞
let obj = {a1:a1,a2:a2,a3:a3};
resolve(obj)
//or
let arr =[a1,a2,a3];
resolve(arr);

 

 

4、鏈式調用函數

then方法提供一個供自定義的回調函數,若傳入非函數,則會忽略當前then方法。
回調函數中會把上一個then中返回的值當做參數值供當前then方法調用。
then方法執行完畢后需要返回一個新的值給下一個then調用(沒有返回值默認使用undefined)。
每個then只可能使用前一個then的返回值。

let func = function() {
    return new Promise((resolve, reject) => {
        resolve('舊值');
    });
};

let nb = function() {
    return '新值';
}

//1、輸出:新值
func().then(function () {
    return nb();
}).then(resp => {
    console.warn(resp);
    console.warn('1 =========<');
});

//then 后回調里面的內容,沒有返回值,所以undefine
//2、輸出:undefine
func().then(function () {
    nb();
}).then(resp => {
    console.warn(resp);
    console.warn('2 =========<');
});

//如果 onFulfilled 不是函數,其必須被忽略
//如果 onFulfilled 是函數:

//這里注意cb()的返回值不是函數,所以會被忽略,而輸出上一個then的返回值

//3、輸出:舊值
func().then(cb()).then(resp => {
    console.warn(resp);
    console.warn('3 =========<');
});

//cb是識別為函數
//4、輸出:新值
func().then(cb).then(resp => {
    console.warn(resp);
    console.warn('4 =========<');
});

 

 

資源:

https://segmentfault.com/a/1190000010420744?utm_source=tag-newest


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM