javaScript ES6 之 Promise 简单的事例

在ES6标准中出现了 Promise(承诺) 类似于回调函数

1:创建Promise的实例

//创建实例
var promise = new Promise(function (resolve, reject) {
      if (success) {
          //执行成功
          resolve(data);
      }else {
         //执行失败
          reject(err);
      }
})
//调用then()方法
promise.then(function(value){
    //成功时调用
}, function(value){
    //失败时调用
})
//或者
promist.then(function(value)){
    //成功时调用
}).cathc(function(value){
    //失败时调用
})

2:Promise结合fetch请求的使用

//定义一个方法,请求数据
requestData = (url, postData)=> {
      return new Promise(function (resolve, reject) {
            //fetch也是一个Promise
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Content-Encoding': 'identity'  //编码方式
                },
                body: JSON.stringify(postData),
            }).then((response) => response.json())
                .then((responseData)=> {
                    resolve(responseData);
                })
                .catch((err)=> {
                    console.log('err', err);
                    reject(err);
                });
            });
      }
}

//调用上面的方法
this.requestData('http://xxx', {'name': 'jj'})
     .then( res=>{
                console.log('success');
     }).catch( err=>{
            //请求失败
            console.log('flied');

3:Promise.all 的用法

Promise.all([promise1, promise2]).then(function(value){

}).catch(function(value){

})

Promise.all中的参数是一个promise的数组[promise1, promise2]:数组中的操作都完成后才会去执行后面的响应

var req1 = new Promise(function(resolve, reject) { 
     // A mock async action using setTimeout
     setTimeout(function() { resolve('First!'); }, 4000);
});
var req2 = new Promise(function(resolve, reject) { 
     // A mock async action using setTimeout
     setTimeout(function() { reject('Second!'); }, 3000);
});
Promise.all([req1, req2]).then(function(results) {
     console.log('Then: ', one);
}).catch(function(err) {
     console.log('Catch: ', err);
});

// From the console:
// Catch: Second!

当Promise.all中出现一个promise执行失败reject,Promise.all会立刻调用catch

4:Promise.race 的用法

Promise.race([promise1, promise2]).then(function(value){

}).catch(function(value){

})

Promise.race的参数也是一个promise的数组[promise1, promise2],不同于Promise.all,Promise.race的数组中只需要一个promise执行成功,Promise.race就响应接下来的操作

var req1 = new Promise(function(resolve, reject) { 
     // A mock async action using setTimeout
     setTimeout(function() { resolve('First!'); }, 8000);
});
var req2 = new Promise(function(resolve, reject) { 
     // A mock async action using setTimeout
     setTimeout(function() { resolve('Second!'); }, 3000);
});
Promise.race([req1, req2]).then(function(one) {
     console.log('Then: ', one);
}).catch(function(one, two) {
     console.log('Catch: ', one);
});

// From the console:
// Then: Second!

这里req2先执行完成,则Promise.race的then回调被执行

你可能感兴趣的:(javaScript ES6 之 Promise 简单的事例)