The usage of ES6 Promise has always been a common test point in interviews and exams. Promise is a constructor. It has familiar methods such as all, reject, and resolve. On the prototype, there are also familiar methods such as then and catch. method.
var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ console.log('执行完成'); resolve('随便什么数据'); }, 2000); });
The constructor of Promise receives one parameter, which is a function, and passes in two parameters: resolve and reject, which respectively represent asynchronous The callback function after the operation is successfully executed and the callback function after the asynchronous operation fails. In fact, it is not accurate to use "success" and "failure" to describe it here. According to standards, resolve sets the status of Promise to fullfiled, and reject sets the status of Promise to rejected. However, we can understand it this way at the beginning, and we will study the concept in detail later.
In the above code, we perform an asynchronous operation, that is, setTimeout. After 2 seconds, "execution completed" is output and the resolve method is called.
Run the code and "execution completed" will be output after 2 seconds. Notice! I just created a new object and did not call it. The function we passed in has already been executed. This is a detail that needs to be paid attention to. So when we use Promise, we usually wrap it in a function and run this function when needed, such as:
function runAsync(){ var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ console.log('执行完成'); resolve('随便什么数据'); }, 2000); }); return p; } runAsync()
At this time you should have two questions: 1. Is there any use in packaging such a function? 2.resolve('Any data'); Is this dry hair?
Let’s continue. At the end of our wrapped function, the Promise object will be returned. That is to say, we get a Promise object by executing this function. Remember that there are then and catch methods on the Promise object, right? This is the power, look at the following code:
runAsync().then(function(data){ console.log(data); //后面可以用传过来的数据做些其他操作 //...... });
Directly call the then method on the return of runAsync(), then receives a parameter, which is a function, and will get it when we call resolve in runAsync The passed parameters. Running this code will output "execution completed" after 2 seconds, followed by "any data".
You should have realized something at this time. It turns out that the function in then is the same as our usual callback function, and can be executed after the asynchronous task runAsync is completed. This is the role of Promise. To put it simply, it can separate the original callback writing method, and after the asynchronous operation is executed, the callback function can be executed in a chain call.
You may be dismissive, but this is what the awesome Promise is capable of? Isn’t it the same if I encapsulate the callback function and pass it to runAsync, like this:
function runAsync(callback){ setTimeout(function(){ console.log('执行完成'); callback('随便什么数据'); }, 2000); } runAsync(function(data){ console.log(data); });
The effect is the same, Why bother using Promise? So the question is, what should I do if there are multiple layers of callbacks? What should we do if callback is also an asynchronous operation and a corresponding callback function is required after execution? You can't define another callback2 and pass it to the callback. The advantage of Promise is that you can continue to write the Promise object in the then method and return it, and then continue to call then to perform callback operations.
So, on the surface, Promise can only simplify the writing of callbacks, but in essence, the essence of Promise is "state ", using the method of maintaining state and passing state to enable the callback function to be called in time, which is much simpler and more flexible than passing the callback function. So the correct scenario for using Promise is this:
runAsync1() .then(function(data){ console.log(data); return runAsync2(); }) .then(function(data){ console.log(data); return runAsync3(); }) .then(function(data){ console.log(data); });
This way, each asynchronous callback can be output in sequence every two seconds. The content, the data passed to resolve in runAsync2, can be obtained in the next then method. The running results are as follows:
Guess how the three functions runAsync1, runAsync2, and runAsync3 are defined? That's right, it's like this
function runAsync1(){ var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ console.log('异步任务1执行完成'); resolve('随便什么数据1'); }, 1000); }); return p; } function runAsync2(){ var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ console.log('异步任务2执行完成'); resolve('随便什么数据2'); }, 2000); }); return p; } function runAsync3(){ var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ console.log('异步任务3执行完成'); resolve('随便什么数据3'); }, 2000); }); return p; }
在then方法中,你也可以直接return数据而不是Promise对象,在后面的then中就可以接收到数据了,比如我们把上面的代码修改成这样:
runAsync1() .then(function(data){ console.log(data); return runAsync2(); }) .then(function(data){ console.log(data); return '直接返回数据'; //这里直接返回数据 }) .then(function(data){ console.log(data); });
那么输出就变成了这样:
到这里,你应该对“Promise是什么玩意”有了最基本的了解。那么我们接着来看看ES6的Promise还有哪些功能。我们光用了resolve,还没用reject呢,它是做什么的呢?事实上,我们前面的例子都是只有“执行成功”的回调,还没有“失败”的情况,reject的作用就是把Promise的状态置为rejected,这样我们在then中就能捕捉到,然后执行“失败”情况的回调。看下面的代码。
function getNumber(){ var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ var num = Math.ceil(Math.random()*10); //生成1-10的随机数 if(num<=5){ resolve(num); } else{ reject('数字太大了'); } }, 2000); }); return p; } getNumber() .then( function(data){ console.log('resolved'); console.log(data); }, function(reason, data){ console.log('rejected'); console.log(reason); } );
getNumber函数用来异步获取一个数字,2秒后执行完成,如果数字小于等于5,我们认为是“成功”了,调用resolve修改Promise的状态。否则我们认为是“失败”了,调用reject并传递一个参数,作为失败的原因。
运行getNumber并且在then中传了两个参数,then方法可以接受两个参数,第一个对应resolve的回调,第二个对应reject的回调。所以我们能够分别拿到他们传过来的数据。多次运行这段代码,你会随机得到下面两种结果:
或者
我们知道Promise对象除了then方法,还有一个catch方法,它是做什么用的呢?其实它和then的第二个参数一样,用来指定reject的回调,用法是这样:
getNumber() .then(function(data){ console.log('resolved'); console.log(data); }) .catch(function(reason){ console.log('rejected'); console.log(reason); });
效果和写在then的第二个参数里面一样。不过它还有另外一个作用:在执行resolve的回调(也就是上面then中的第一个参数)时,如果抛出异常了(代码出错了),那么并不会报错卡死js,而是会进到这个catch方法中。请看下面的代码:
getNumber() .then(function(data){ console.log('resolved'); console.log(data); console.log(somedata); //此处的somedata未定义 }) .catch(function(reason){ console.log('rejected'); console.log(reason); });
在resolve的回调中,我们console.log(somedata);而somedata这个变量是没有被定义的。如果我们不用Promise,代码运行到这里就直接在控制台报错了,不往下运行了。但是在这里,会得到这样的结果:
也就是说进到catch方法里面去了,而且把错误原因传到了reason参数中。即便是有错误的代码也不会报错了,这与我们的try/catch语句有相同的功能。
Promise的all方法提供了并行执行异步操作的能力,并且在所有异步操作执行完后才执行回调。我们仍旧使用上面定义好的runAsync1、runAsync2、runAsync3这三个函数,看下面的例子:
Promise .all([runAsync1(), runAsync2(), runAsync3()]) .then(function(results){ console.log(results); });
用Promise.all来执行,all接收一个数组参数,里面的值最终都算返回Promise对象。这样,三个异步操作的并行执行的,等到它们都执行完后才会进到then里面。那么,三个异步操作返回的数据哪里去了呢?都在then里面呢,all会把所有异步操作的结果放进一个数组中传给then,就是上面的results。所以上面代码的输出结果就是:
有了all,你就可以并行执行多个异步操作,并且在一个回调中处理所有的返回数据,是不是很酷?有一个场景是很适合用这个的,一些游戏类的素材比较多的应用,打开网页时,预先加载需要用到的各种资源如图片、flash以及各种静态文件。所有的都加载完后,我们再进行页面的初始化。
all方法的效果实际上是「谁跑的慢,以谁为准执行回调」,那么相对的就有另一个方法「谁跑的快,以谁为准执行回调」,这就是race方法,这个词本来就是赛跑的意思。race的用法与all一样,我们把上面runAsync1的延时改为1秒来看一下:
Promise .race([runAsync1(), runAsync2(), runAsync3()]) .then(function(results){ console.log(results); });
这三个异步操作同样是并行执行的。结果你应该可以猜到,1秒后runAsync1已经执行完了,此时then里面的就执行了。结果是这样的:
你猜对了吗?不完全,是吧。在then里面的回调开始执行时,runAsync2()和runAsync3()并没有停止,仍旧再执行。于是再过1秒后,输出了他们结束的标志。
这个race有什么用呢?使用场景还是很多的,比如我们可以用race给某个异步请求设置超时时间,并且在超时后执行相应的操作,代码如下:
//请求某个图片资源 function requestImg(){ var p = new Promise(function(resolve, reject){ var img = new Image(); img.onload = function(){ resolve(img); } img.src = 'xxxxxx'; }); return p; } //延时函数,用于给请求计时 function timeout(){ var p = new Promise(function(resolve, reject){ setTimeout(function(){ reject('图片请求超时'); }, 5000); }); return p; } Promise .race([requestImg(), timeout()]) .then(function(results){ console.log(results); }) .catch(function(reason){ console.log(reason); });
requestImg函数会异步请求一张图片,我把地址写为"xxxxxx",所以肯定是无法成功请求到的。timeout函数是一个延时5秒的异步操作。我们把这两个返回Promise对象的函数放进race,于是他俩就会赛跑,如果5秒之内图片请求成功了,那么遍进入then方法,执行正常的流程。如果5秒钟图片还未成功返回,那么timeout就跑赢了,则进入catch,报出“图片请求超时”的信息。运行结果如下:
相关文章:
详细解读JavaScript编程中的Promise使用_基础知识
JavaScript编程中的Promise使用大全_基础知识
相关视频:
The above is the detailed content of Basic knowledge of js that is often tested in interviews and written tests: usage of ES6 Promise. For more information, please follow other related articles on the PHP Chinese website!