JavaScript ES6 Promise objects

Explanation

Node.js, the asynchronous (Async) callback is known, the use of asynchronous, improve the efficiency of the program, however, poor code readability.
If there are a few asynchronous operation, returning after a operation after operation is finished before the data required to perform a go, if you use Node.js, you need to go on a nested layers, Promised target is proposed for this problem out solutions.

basic concepts

Promise object state:

  1. pending
    The initial state, also known as undecided state, is the initialization Promise, a state after the actuator executor function call.
  2. fulfilled
    Completion status, meaning that the success of the asynchronous operation.
  3. rejected
    Failed state, it means an asynchronous operation failed.

These are the only state transition pending-> fulfilled pending-> rejected, returns the status of this main object Promise is a value returned by the promise1.then () Method:

State unidirectional conversion is irreversible, the state has been determined (fulfilled / rejected) back into the original state can not be (Pending)

When the state is rejected, the promise can not continue down, we need to add a catch exception information obtained
callback function:

  • resolve
    When pendingstate to fulfilledstate when the callback (operation succeeded)
  • reject
    When pendingstate to rejectedstate when the callback (operation failed)

method:

  • then()
  • catch()
  • all()
  • race()

Basic use

new Promise(function(resolve,reject){
    //这里面实现异步操作,ajax等..
    //获得结果,回调传参
    if(/*success*/){
        resolve();
    }else{
        reject();
    }
});
//虽然没有去执行setTimeOut函数,但是Promise会自动执行,所以,一般需要将Promise写在一个function里面
new Promise(function(resolve,reject){
    setTimeout(function(){
        let num = Math.random();
        //当随机数小于0.5,当前promise完成了执行
        if(num<0.5){
            resolve(num);
        }else{
            reject("错误,num>=0.5");
        }
        console.log('执行完成');
    },2000);
});
let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        let num = Math.random();
        //当随机数小于0.5,当前promise完成了执行
        if(num<0.5){
            resolve(num);
        }else{
            reject(num);
        }
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    //这里的data是之前resolve中的回调参数
    console.log(data);
},function(error){
    //这里的error是之前resolve中的回调参数
    console.log("错误原因为"+error);
});

Advanced Use

then()

Promise then(fun(resolve,reject))

p.then(function(data){
    //这里的data是之前resolve中的回调参数
    console.log(data);
},function(data){
    //这里的data是之前resolve中的回调参数
    console.log("错误");
    console.log(data);
});

The method then, the callback parameter may be received and processed, then the method returns a Promise object. Here, our main concern is the status of the return Promise objects.

This state can return to the main object Promise is the value returned by the method according to promise1.then ():

  1. If the then () method returns a parameter value, the returned reception state will become Promise.
  2. If then () method throws an exception, then the returned Promise will become refused to state.
  3. If then () method call resolve () method, the return of Promise will be receiving state.
  4. If then () method call reject () method, the return of rejected Promise will become state.
  5. If then () method returns an unknown state (pending) a new instance of Promise, then the new Promise return is unknown state.
  6. If the then () method is not explicitly specified resolve (data) / time reject (data) / return data, then the new receiving state is returned Promise, can pass down layer by layer.
let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        let num = Math.random();
        //当随机数小于0.5,当前promise完成了执行
        if(num<0.5){
            resolve(num);
        }else{
            reject(num);
        }
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    //用上次获得的数据执行相关的异步操作
},function(error){
    //出现错误,处理错误信息
});
let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        resolve("hello");
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    console.log(data);
}).then(function(){
    setTimeout(function(){
        console.log("过了5s,继续执行");
    },5000);
});
let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        resolve("hello");
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    console.log(data);
    //处理完数据之后,返回新的数据,给下次异步操作处理
    return "this is new data"
}).then(function(data){
    setTimeout(function(){
        console.log("过了5s,继续执行");
        console.log(data);
    },5000);
});

catch()

As the catch () method and the then () method returns a new Promise objects, it is mainly used when capturing abnormal asynchronous operation.

Thus, we usually omit the then second parameter () method, the error processing control to the catch () function behind it.

The following two code blocks, the functions are the same.

let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        let num = Math.random();
        //当随机数小于0.5,当前promise完成了执行
        if(num<0.5){
            resolve(num);
        }else{
            reject(num);
        }
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    //用上次获得的数据执行相关的异步操作
},function(error){
    //出现错误,处理错误信息
});
let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        let num = Math.random();
        if(num<0.5){
            resolve(num);
        }else{
            reject(num);
        }
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    //用上次获得的数据执行相关的异步操作
}).catch(function(error){
    //处理错误信息
});

race()

Its argument is iterable objects, such as arrays

Two asynchronous tasks simultaneously sending a request to the same url, who should get data, further data obtained in asynchronous task that will be discarded

//2s后输出“执行完成1”
let p =new Promise(function(resolve){
    setTimeout(function(){
        resolve("hello");
        console.log('执行完成1');
    },2000);
});
//1s后输出“执行完成2”
let p1 =new Promise(function(resolve){
    setTimeout(function(){
        resolve("hello 2");
        console.log('执行完成2');
    },1000);
});
//两个异步任务同时开始
let mixedPromisesArray = [p,p1];
let p3 = Promise.race(mixedPromisesArray).then(data=>{
    //这里的data为hello 2,hello被丢弃
    console.log(data);
});

all()

Iterative parameters are also objects, such as arrays

It may be used when several tasks running in parallel

When a task fails, the status will change to reject

//2s后输出“执行完成1”
let p =new Promise(function(resolve){
    setTimeout(function(){
        resolve("hello");
        console.log('执行完成1');
    },2000);
});
//1s后输出“执行完成2”
let p1 =new Promise(function(resolve){
    setTimeout(function(){
        resolve("hello 2");
        console.log('执行完成2');
    },1000);
});
//两个异步任务同时开始
let mixedPromisesArray = [p,p1];
let p3 = Promise.all(mixedPromisesArray).then(data=>{
    //这里的data数组,存放着之前两个异步回调传的数据
    console.log(data);
});

reference

ES6 usage of Promise of
MDN Promise

Explanation

Node.js, the asynchronous (Async) callback is known, the use of asynchronous, improve the efficiency of the program, however, poor code readability.
If there are a few asynchronous operation, returning after a operation after operation is finished before the data required to perform a go, if you use Node.js, you need to go on a nested layers, Promised target is proposed for this problem out solutions.

basic concepts

Promise object state:

  1. pending
    The initial state, also known as undecided state, is the initialization Promise, a state after the actuator executor function call.
  2. fulfilled
    Completion status, meaning that the success of the asynchronous operation.
  3. rejected
    Failed state, it means an asynchronous operation failed.

These are the only state transition pending-> fulfilled pending-> rejected, returns the status of this main object Promise is a value returned by the promise1.then () Method:

State unidirectional conversion is irreversible, the state has been determined (fulfilled / rejected) back into the original state can not be (Pending)

When the state is rejected, the promise can not continue down, we need to add a catch exception information obtained
callback function:

  • resolve
    When pendingstate to fulfilledstate when the callback (operation succeeded)
  • reject
    When pendingstate to rejectedstate when the callback (operation failed)

method:

  • then()
  • catch()
  • all()
  • race()

Basic use

new Promise(function(resolve,reject){
    //这里面实现异步操作,ajax等..
    //获得结果,回调传参
    if(/*success*/){
        resolve();
    }else{
        reject();
    }
});
//虽然没有去执行setTimeOut函数,但是Promise会自动执行,所以,一般需要将Promise写在一个function里面
new Promise(function(resolve,reject){
    setTimeout(function(){
        let num = Math.random();
        //当随机数小于0.5,当前promise完成了执行
        if(num<0.5){
            resolve(num);
        }else{
            reject("错误,num>=0.5");
        }
        console.log('执行完成');
    },2000);
});
let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        let num = Math.random();
        //当随机数小于0.5,当前promise完成了执行
        if(num<0.5){
            resolve(num);
        }else{
            reject(num);
        }
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    //这里的data是之前resolve中的回调参数
    console.log(data);
},function(error){
    //这里的error是之前resolve中的回调参数
    console.log("错误原因为"+error);
});

Advanced Use

then()

Promise then(fun(resolve,reject))

p.then(function(data){
    //这里的data是之前resolve中的回调参数
    console.log(data);
},function(data){
    //这里的data是之前resolve中的回调参数
    console.log("错误");
    console.log(data);
});

The method then, the callback parameter may be received and processed, then the method returns a Promise object. Here, our main concern is the status of the return Promise objects.

This state can return to the main object Promise is the value returned by the method according to promise1.then ():

  1. If the then () method returns a parameter value, the returned reception state will become Promise.
  2. If then () method throws an exception, then the returned Promise will become refused to state.
  3. If then () method call resolve () method, the return of Promise will be receiving state.
  4. If then () method call reject () method, the return of rejected Promise will become state.
  5. If then () method returns an unknown state (pending) a new instance of Promise, then the new Promise return is unknown state.
  6. If the then () method is not explicitly specified resolve (data) / time reject (data) / return data, then the new receiving state is returned Promise, can pass down layer by layer.
let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        let num = Math.random();
        //当随机数小于0.5,当前promise完成了执行
        if(num<0.5){
            resolve(num);
        }else{
            reject(num);
        }
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    //用上次获得的数据执行相关的异步操作
},function(error){
    //出现错误,处理错误信息
});
let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        resolve("hello");
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    console.log(data);
}).then(function(){
    setTimeout(function(){
        console.log("过了5s,继续执行");
    },5000);
});
let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        resolve("hello");
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    console.log(data);
    //处理完数据之后,返回新的数据,给下次异步操作处理
    return "this is new data"
}).then(function(data){
    setTimeout(function(){
        console.log("过了5s,继续执行");
        console.log(data);
    },5000);
});

catch()

As the catch () method and the then () method returns a new Promise objects, it is mainly used when capturing abnormal asynchronous operation.

Thus, we usually omit the then second parameter () method, the error processing control to the catch () function behind it.

The following two code blocks, the functions are the same.

let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        let num = Math.random();
        //当随机数小于0.5,当前promise完成了执行
        if(num<0.5){
            resolve(num);
        }else{
            reject(num);
        }
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    //用上次获得的数据执行相关的异步操作
},function(error){
    //出现错误,处理错误信息
});
let p =new Promise(function(resolve,reject){
    setTimeout(function(){
        let num = Math.random();
        if(num<0.5){
            resolve(num);
        }else{
            reject(num);
        }
        console.log('执行完成');
    },2000);
});
p.then(function(data){
    //用上次获得的数据执行相关的异步操作
}).catch(function(error){
    //处理错误信息
});

race()

Its argument is iterable objects, such as arrays

Two asynchronous tasks simultaneously sending a request to the same url, who should get data, further data obtained in asynchronous task that will be discarded

//2s后输出“执行完成1”
let p =new Promise(function(resolve){
    setTimeout(function(){
        resolve("hello");
        console.log('执行完成1');
    },2000);
});
//1s后输出“执行完成2”
let p1 =new Promise(function(resolve){
    setTimeout(function(){
        resolve("hello 2");
        console.log('执行完成2');
    },1000);
});
//两个异步任务同时开始
let mixedPromisesArray = [p,p1];
let p3 = Promise.race(mixedPromisesArray).then(data=>{
    //这里的data为hello 2,hello被丢弃
    console.log(data);
});

all()

Iterative parameters are also objects, such as arrays

It may be used when several tasks running in parallel

When a task fails, the status will change to reject

//2s后输出“执行完成1”
let p =new Promise(function(resolve){
    setTimeout(function(){
        resolve("hello");
        console.log('执行完成1');
    },2000);
});
//1s后输出“执行完成2”
let p1 =new Promise(function(resolve){
    setTimeout(function(){
        resolve("hello 2");
        console.log('执行完成2');
    },1000);
});
//两个异步任务同时开始
let mixedPromisesArray = [p,p1];
let p3 = Promise.all(mixedPromisesArray).then(data=>{
    //这里的data数组,存放着之前两个异步回调传的数据
    console.log(data);
});

reference

ES6 usage of Promise of
MDN Promise

Guess you like

Origin www.cnblogs.com/chaoyang123/p/11549776.html
Recommended