Home > Article > Web Front-end > What you need to know to get started with Promise
This time I will bring you what you must know when getting started with Promise. What are the precautions that you must know when getting started with Promise. Here are practical cases, let’s take a look.
Promise is a solution for asynchronous programming. Syntactically speaking, Promise is an object from which messages for asynchronous operations can be obtained.
PromiseConstructor functionAccepts a function as a parameter, and the two parameters of the function are resolve and reject. They are two functions, provided by the JavaScript engine.
The function of the resolve function is to change the state of the Promise object from "uncompleted" to "successful" (that is, from Pending to Resolved), When the asynchronous operation is successful Call and pass the result of the asynchronous operation as a parameter.
The function of the reject function is to change the status of the Promise object from "uncompleted" to "failed" (that is, from Pending to Rejected), When the asynchronous operation fails Call and pass the error reported by the asynchronous operation as a parameter.
Thethen method can accept two callback functions as parameters. The first callback function is called when the state of the Promise object changes to Resolved, and the second callback function is called when the state of the Promise object changes to Reject.
var promise = new Promise( //异步执行,Promise对象创建后会被立即执行 function (resolve,reject) { //耗时很长的异步操作 if('异步处理成功') { resolve(); //数据处理成功时调用 } else { reject(); //数据处理失败时调用 } } )//Promise实例生成以后,可以用then方法分别指定Resolved状态和Reject状态的回调函数。promise.then( function A() { //数据处理成功后执行 }, function B() { //数据处理失败后执行 } )
Let’s take a simple example to simulate the running process of asynchronous operation success and asynchronous operation failure functions.
console.log('starting' promise = Promise("2秒后,我运行了"'异步操作成功了'); }, 2000'异步操作成功后执行我:''异步操作失败后执行我:''我也运行了'
知代码3处的return 'hello' 语句在新建的new Promise对象中并没有被当作参数返回给then()函数内.那么会不会返回给promise了呢?我们用一段代码来测试一下
console.log('starting');var promise = new Promise(function(resolve, reject) { setTimeout(function() { console.log("2秒后,我运行了"); resolve('异步操作成功了'); //1 //reject('异步操作失败了'); //2 return 'hello'; }, 2000) }) promise.then(function (value) { console.log('异步操作成功后执行我:',value); },function (value) { console.log('异步操作失败后执行我:',value); } ) console.log('我也运行了'); console.log(promise); setTimeout(function () { console.log('5秒后,我执行了'); console.log(promise); },5000);//starting//我也运行了//Promise { pending } //[[PromiseStatus]]:"pending" //[[PromiseValue]]:undefined //proto:Promise {constructor: , then: , catch: , …}//2秒后,我运行了//异步操作成功后执行我: 异步操作成功了//5秒后,我执行了//Promise { resolved } //[[PromiseStatus]]:"resolved" //[[PromiseValue]]:"异步操作成功了" //proto:Promise {constructor: , then: , catch: , …}
It can be seen from the execution results that the variable promise is still an instance of the new Promise object. Therefore, although the return statement is executed, it will not have any impact on the promise instance, which is equivalent to non-existence.
As can be seen from the code tested above, Promise objects have the following two characteristics.
(1) The state of the object is not affected by the outside world. The Promise object represents an asynchronous operation and has three states: Pending (in progress), Resolved (completed, also known as Fulfilled) and Rejected (failed). Only the result of the asynchronous operation can determine which state the current state is,
(2) Once the state changes, it will not change again, and the result can be obtained at any time. There are only two possibilities for the state of a Promise object to change: from Pending to Resolved and from Pending to Rejected. As long as these two situations occur, the state will be solidified and will not change again, and will maintain this result. Even if the change has already occurred, if you add a callback function to the Promise object, you will get the result immediately. This is completely different from an event. The characteristic of an event is that if you miss it and listen again, you will not get the result.
We will call the resolve function when the asynchronous operation is successful, and its function is to change the state of the Promise object from Pending becomes Resolved, and the result of the asynchronous operation is passed as a parameter to the formal parameter of the first function in the then() method.
So what is the difference between when the parameter passed in is a value and when the parameter passed in is a promise object. Let's look at an example.
When the parameter passed in is a value:
var time = new Date();var promise = new Promise(function(resolve, reject) { setTimeout(function() { console.log("1秒后,我运行了"); resolve('异步操作成功了'); //1 }, 2000) }).then(function (value) { console.log(value,new Date() - time); })//执行的输出结果为://2秒后,我运行了//异步操作成功了 1002
After about a second or so, we can see that in the callback method of the resolved state, we print out the content in the above comment . We can pass the results of the operation through the resolve method and then use these results in the callback method.
What if we pass in a Promise instance in resolve?
time = promise = Promise("2秒后,我运行了"'异步操作成功了'); 2000 promise2 = Promise(1000 Date() -
promise2 prints out the result after 2 seconds. Strange, didn't we set promise2 to be executed after 1 second?
Simply put, it is because the resolve() function in promise2 passes in the promise object. At this time, the state of the promise object determines the state of the promise, and the return value is passed to the promise.
Promise/A+ stipulates [[Resolve]](promise, x)
2.3.2. If x is a promise instance, then x The status of is used as the status of promise
2.3.2.1. If the status of x is pending, then the status of promise is also pending until the status of x changes.
2.3.2.2. If the status of x is fulfilled, the status of promise is also fulfilled, and the immutable value of x is used as the immutable value of promise.
2.3.2.3.如果x的状态为rejected, promise的状态也为rejected, 并且以x的不可变原因作为promise的不可变原因。
2.3.4.如果x不是对象或函数,则将promise状态转换为fulfilled并且以x作为promise的不可变值。
Promise实例具有then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。它的作用是为Promise实例添加状态改变时的回调函数。 前面说过,then方法的第一个参数是Resolved状态的回调函数,第二个参数(可选)是Rejected状态的回调函数。
then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。
var promise = new Promise(function(resolve, reject) { setTimeout(function() { console.log("2秒后,我运行了"); resolve('异步操作成功了'); //1 }, 2000) }) promise.name = 'promise'; console.log('promise:',promise)var promise2 = promise.then(function (value) { console.log(value); }) promise2.name = 'promise2'; console.log('promise2:',promise2);// promise:// Promise { pending }// [[PromiseStatus]]:"pending"// [[PromiseValue]]:undefined// name:"promise"// proto:Promise {constructor: , then: , catch: , …}// promise2:// Promise { pending }// [[PromiseStatus]]:"pending"// [[PromiseValue]]:undefined// name:"promise2"// proto:Promise {constructor: , then: , catch: , …}
我们可以知道promise.then()方法执行后返回的是一个新的Promise对象。也就是说上面代码中的promise2是一个Promise对象,它的实现效果和下面的代码是一样的,只不过在then()方法里,JS引擎已经自动帮我们做了。
promise2 = new Promise(function (resolve,reject) {})
既然在then()函数里已经自动帮我实现了一个promise对象,但是我要怎么才能给resolve()或reject()函数传参呢?其实在then()函数里,我们可以用return()的方式来给promise2的resolve()或reject()传参。看一个例子。
promise = Promise("2秒后,我运行了"'异步操作成功了'); }, 2000 promise2 = promise.then( (1 promise3 = promise2.then('is:''error:'= 'promise2'3000
.then(null, rejection),用于指定异步操作发生错误时执行的回调函数。下面我们做一个示例。
var promise = new Promise(function(resolve, reject) { setTimeout(function () { reject('error'); },2000); }).then(null,function(error) { console.log('rejected', error) });//rejected error
我们知道then()方法执行后返回的也是一个promise对象,因此也可以调用then()方法,但这样的话为了捕获异常信息,我们就需要为每一个then()方法绑定一个.then(null, rejection)。由于Promise对象的错误信息具有“冒泡”性质,错误会一直向后传递,直到被捕获为止。因此Promise为我们提供了一个原型上的函数Promise.prototype.catch()来让我们更方便的 捕获到异常。
我们看一个例子
var promise = new Promise(function(resolve, reject) { setTimeout(function () { reject('error'); },2000); }).then(function(value) { console.log('resolve', value); }).catch(function (error) { console.log(error); })//运行结果//error
上面代码中,一共有二个Promise对象:一个由promise产生,一个由then产生。它们之中任何一个抛出的错误,都会被最后一个catch捕获。
但是如果用.then(null, rejection)方法来处理错误信息,我们需要在每一个rejection()方法中返回上一次异常信息的状态,这样当调用的then()方法一多的时候,对会对代码的清晰性和逻辑性造成影响。
所以,一般来说,不要在then方法里面定义Reject状态的回调函数(即then的第二个参数),总是使用catch方法。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of What you need to know to get started with Promise. For more information, please follow other related articles on the PHP Chinese website!