Promise learning

table of Contents

What is Promise?

 Why Promise?

Create a Promise

A simple example

Basic usage of Promise 


What is Promise?

Explanation of MDN:

Promise  final status (completed or failed) for indicating a target asynchronous operations, and the result value of the asynchronous operation.

 Why Promise?

Prior to promise occurs, you can use asynchronous callbacks to perform asynchronous operations:

setTimeout(function() {
    console.log('taskA, asynchronous');
}, 0);
console.log('taskB, synchronize');
//while(true);

-------output-------
taskB, synchronize
taskA, asynchronous

Note: Timer delay time is 0, taskA or late execution in taskB. This is because the timer is asynchronous, asynchronous tasks will be executing the synchronization tasks in all the current script will be performed. At this time, if the synchronization code contains an infinite loop, then the asynchronous task will not be executed, because the task of blocking the process of synchronization.

Promise objects are also used for asynchronous operation, and that it has what advantage?

Promise the real power lies in its multiple chained calls , avoid deeply nested callback. Use  then be "chained callback", the asynchronous operation to the synchronous operation of processes that out.

E.g:

the sendRequest ( '...', '') .then ( function (DATAl) { 
    the console.log ( 'first request succeeds, it returns the data is:' , DATAl);
     return the sendRequest ( 'test2.html' , DATAl); 
.}) the then ( function (DATA2) { 
    the console.log ( 'second request succeeds, it returns the data is:' , DATA2);
     return the sendRequest ( 'test3.html' , DATA2); 
}). the then ( function (DATA3) { 
    console.log ( 'third request succeeds, it returns the data is:' , DATA3); 
}). catch ( function (error) {
     // with catch capture previous error 
    console.log ( "Sorry, the request fails, this failure information is: ' ,error); 
});

 

Create a Promise

myFirstPromise = const new new Promise ((Resolve, Reject) => {
   // do some asynchronous operation, eventually calling one of the following two: 
  //
   //    Resolve (someValue); Fulfilled // 
  // or 
  //    Reject ( " reason failure "); // Rejected 
});

If you want the functionality of a function has the Promise, just let it returns a Promise to:

function myAsyncFunction(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onload = () => resolve(xhr.responseText);
    xhr.onerror = () => reject(xhr.statusText);
    xhr.send();
  });
};

A simple example

var promise1 = new Promise(function(resolve,reject){
  setTimeout(function(){
    resolve('foo');
  },3000);
});

promise1.then(function(value){   // 这个value就是resolve函数的参数
  console.log(value);
});

console.log(promise1);

----output----

[object Promise]

"foo"

Basic usage of Promise 

A Promise has the following states:

  • the Pending : The initial state is neither a success nor a failure state.
  • Fulfilled : it means that the operation completed successfully.
  • Rejected : it means that the operation failed.

 Promise of change in the state and there are only two: one by the pending changes to fulfilled; the second is the pending changes to rejected.

Wherein when one of these occurs, the processing method (handlers) then bound object Promise method is invoked.

Note: Promise will be executed immediately once the new can not be canceled. This is also one of its drawbacks.

Promise to accept a "function" as a parameter, the function of the two parameters are the resolve and reject. These two functions that is the "callback", provided by the JavaScript engine.

Test = const new new Promise ( function (Resolve, Reject) {
     IF (...) { 
        Resolve (...); // successful asynchronous operations 
    } the else { 
        Reject (error);     // asynchronous operation failed 
    } 
});

resolve function effect: upon successful call asynchronous operation, and the result of the asynchronous operation, to pass out as a parameter; 
action reject function: call failure when an asynchronous operation, and the asynchronous operation of the reported error , to pass out as a parameter.

test.then(function(data){
    ...// data是resolve函数中传入的参数,表示异步操作成功的数据
},function(error){ ...// 这第二个回调函数不是必须的 });

After generating Promise example, specify a callback function can resolve state by state and then reject method.

 then the method specified in the callback function will be executed only after the script is finished all the synchronization tasks currently. The Promise performed immediately after the creation.

Guess you like

Origin www.cnblogs.com/ZLDJ-15-516/p/11027286.html