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