首页 > 技术文章 > 关于Promise 简单使用理解

inzaghihao 2017-11-01 15:13 原文

在学一个新的知识的时候,我的总结是首先要具备相关的基础知识,其次就是可以静下心来能看进去去理解,看一两遍不懂,就看四五遍,甚至六七遍,每一遍都认真努力理解,总会学会的。

Promise是一个构造函数,自己身上有all、reject、resolve这几个眼熟的方法,原型上有then、catch等同样很眼熟的方法。这么说用Promise new出来的对象肯定就有then、catch方法。没错!

var p = new Promise(function(resolve, reject){
    //做一些异步操作
    setTimeout(function(){
        console.log('执行完成');
        resolve('随便什么数据');
    }, 2000);
});

Promise的构造函数接收一个参数,是函数,并且传入两个参数:resolve,reject,分别表示异步操作执行成功后的回调函数和异步操作执行失败后的回调函数。按照标准来讲,resolve是将Promise的状态置为fullfiled,reject是将Promise的状态置为rejected。

注意!我只是new了一个对象,并没有调用它,我们传进去的函数就已经执行了,这是需要注意的一个细节。所以我们用Promise的时候一般是包在一个函数中,在需要的时候去运行这个函数

function runAsync(){
    return new Promise(function(resolve, reject){
        //做一些异步操作
        setTimeout(function(){
            console.log('执行完成');
            resolve('接受成功数据');
        }, 2000);
    });         
}
runAsync().then((text)=>{
    console.log('执行完成'+text);
},()=>{
    console.log('执行失败');
})

 

我们前面的例子都是只有“执行成功”的回调,还没有“失败”的情况,reject的作用就是把Promise的状态置为rejected,这样我们在then中就能捕捉到,然后执行“失败”情况的回调。看下面的代码。

function getNumber(){
    return new Promise(function(resolve, reject){
        //做一些异步操作
        setTimeout(function(){
            var num = Math.ceil(Math.random()*10); //生成1-10的随机数
            if(num<=5){
                resolve(num);
            }
            else{
                reject('数字太大了'+num);
            }
        }, 1000);
    });            
}

getNumber().then(
    function(data){
        console.log('resolved');
        console.log(data);
    }, 
    function(reason, data){
        console.log('rejected');
        console.log(reason);
    }
);

运行getNumber并且在then中传了两个参数,then方法可以接受两个参数,第一个对应resolve的回调,第二个对应reject的回调。(或者用catch方法)所以我们能够分别拿到他们传过来的数据

getNumber()
.then(function(data){
    console.log('resolved');
    console.log(data);
})
.catch(function(reason){
    console.log('rejected');
    console.log(reason);
});

 

all的用法

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。所以上面代码的输出结果就是:

race的用法

all方法的效果实际上是「谁跑的慢,以谁为准执行回调」,那么相对的就有另一个方法「谁跑的快,以谁为准执行回调」,这就是race方法,这个词本来就是赛跑的意思。race的用法与all一样,我们把上面runAsync1的延时改为1秒来看一下:

这三个异步操作同样是并行执行的。结果你应该可以猜到,1秒后runAsync1已经执行完了,此时then里面的就执行了。结果是这样的:

 

 

 贴个例子:

function loadImageAsync(url) {
  return new Promise(function(resolve, reject) {
    var image = new Image();

    image.onload = function() {
      resolve(image);
    };

    image.onerror = function() {
      reject(new Error('Could not load image at ' + url));
    };

    image.src = url;
  });
}

function getNumber(){
    return new Promise(function(resolve, reject){
        //做一些异步操作
        setTimeout(function(){
            var num = Math.random()*10 | 0; //生成1-10的随机数
            if(num<=5){
                resolve(num);
            }
            else{
                reject('数字太大了'+num);
            }
        }, 1000);
    });            
}
// loadImageAsync('https://mengera88.github.io/images/avatar.gif').then((image)=>{
//     console.log('down');
//     document.getElementById('div').appendChild(image)
// },()=>{

// })

Promise.all([getNumber(),loadImageAsync('https://mengera88.github.io/images/avatar.gif')]).then((res)=>{
    console.log(res)
})

 

 

原文链接:http://www.cnblogs.com/lvdabao/p/es6-promise-1.html

 

推荐阅读