Promise , fetch Api ,blueBird,Q,When

Promise which the solution of async programmer is the original obj presented by ecmaScript 6 , it’s better than the asynchronous callback was presented by community ;

Promise is a object that can get asynchronous message, then method of then return the promise obj but different from the original promise obj

the second argument of then method is the same to .catch(); but the catch is optimized.

code:

let Promise = new Promise(function(res,rej){
    res("suc");

}).then( res=>{

    console.log(`the async of network's result is ${res}`);

}).catch((err)=>{

    console.log(err);

});


Below the code and the role of the same above


let Promise = new Promise((res,rej)=>{res("suc");})
.then(
  res=>{console.log(`the async of network's result is ${res}`);},
  err=>{console.log(err)}
);
The role of the resolve method is to bring the results out of the state of promise from pending to success,the role of the reject method is to bring the error results out of when the state of promise form pending to error.
let promise = new Promise(function(resolve, reject) {
  console.log('Promise');
  resolve();
});

promise.then(function() {
  console.log('Resolved.');
});

console.log('Hi!');

// Promise
// Hi!
// Resolved

// the output of Hi is before than Resolved because of Then method assign //callback that will execute after synchronous task 

core:

the es 6 promise have the same aim with bluebird to solve the callback trap , but es6 is late appear than blue bird
below is use promise , async , and normal way deal with callback issue

<script>
//refer : http://www.tuicool.com/articles/bUNj6ji
// blue bird provide promise api
// you can use es6 promise solve the callback
// you can use generator
//todo:// before es 6 Q,when.js,bluebird solve the callback use base promise 
    export default{
        data(){
            return{
                msg:'hello vue',
                url:"",
                url1:"",
            }
        },
        mounted:function(){
          this.getDataByBlueBird();

          window.p = pp;

        },


        methods:{

            getDataByPromise(){
                //request by promise
               this.$http.get(this.url).then(res=>{
                //deal with the first request
                console.log(res);
                return this.$http.get(`${this.url1}?msg=${res.data.msg}`)
              }).then(res=>{
                //deal with the second request
                console.log(res);
            }).catch(err=>{
                //deal with the error
                console.log(err);
            })

            },

            getDataByNormal(){
            // this.$http.get('').then(res=>{console.log()}).catch(err=>{console.log(err.statusText)})
           // vue promise and request intercept
            this.$http.get(this.url).then(res=>{
                  console.log(res);
                  //todo:// the next http
                  this.$http.get(this.url1).then(res=>{
                      console.log(res)
                  })
            })
            //catch the error all include inner error
            .catch(err=>{console.log(err.statusText)});

             // the callback trap isn't resolve by v-resource but promise just as blue bird

            },

            // the promise.all can't sure the result by httpRequest order
            getDataByPromiseAll(){

                const promises = [this.url,this.url1].map(item=>{
                      //todo://  return promise object the response order same to request order
                      return this.$http.get(item);

                });

                Promise.all(promises).then(res=>{
                    //todo:// the result is response data array
                    console.log(res);

                })
            },

            getDataByBlueBird(){
                  // return a promise obj you can .then the first argument of then is the last request res
                  // todo:// make every callback become a alone chunk
                  Promise.resolve()
                  .then(()=>{
                      return this.$http.get(this.url);
                  }).then(res =>{
                        console.log(res);
                        return this.$http.get(this.url1);
                  }).then(res =>{
                      console.log(res);
                  });

            },

            //async and await is better the generator , async like * await like yield
            //async function return promise obj , you can use then add callback . the function will wait when
            //execute await
            getDataByAsync(){
                let getData = async ()=>{
                     //todo:// if not use ()=> this will be undefined because ...
                     var f1 =  await this.$http.get(this.url);
                     var f2 = await this.$http.get(`${this.url1}token=${f1.data.code}`);
                      console.log(f1.data);
                      console.log(f2.data);
                }

                getData();

            },


        },

        components:{
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章