[ES6] Promise usage

ES6 - Promise usage

 

Reference: https://www.jianshu.com/p/7e60fc1be1b2

https://www.jianshu.com/p/eb474a90cf46?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

Promise concept

The so-called Promise, it simply is a container, which holds the event will end sometime in the future (usually an asynchronous operation) results. Syntactically, Promise is an object, you can get messages from the asynchronous operation of it. Promise to provide a unified API, a variety of asynchronous operations can be handled the same way. 
Promise object has the following two characteristics. 
( 1 state) is not subject to outside influence. Promise object represents an asynchronous operation, there are three states: pending (in progress), fulfilled (been successful) and rejected (failed). Only results of asynchronous operations, you can decide what kind of current state, no other operations can change that state. Promise This is the origin of the name, which in English means "commitment", he said other means can not be changed. 
( 2 ) Once the status change, it will not change, at any time this result can be obtained. Promise object changes state, only two possibilities: from pending from pending changes to become fulfilled and rejected. As long as these two things happens on the solidification state, it will not be changed and will keep the result, then called resolved (finalized). If the change has occurred, you add a callback function to Promise object will immediately get this result. This event (Event) is completely different, the characteristics of the event is, if you missed it, go listen, is not the result. 
Note that, in order to facilitate the drafting, later in this chapter refers only fulfilled resolved unified state, does not contain rejected state. 
With Promise object, the process may be asynchronous operation to synchronous operation expressed, to avoid deeply nested callback function. 

Further, Promise object provides a unified interface, so that the control of asynchronous operations easier.
Promise also has some drawbacks. First of all, you can not cancel the Promise, it will be executed immediately once the new can not be canceled midway. Secondly, if you do not set a callback function, Promise 
internal error thrown, it does not react to the outside. Third, when in a pending 
state, progress is currently no way of knowing where a stage (beginning or nearing completion). 
If certain events continue to occur repeatedly, in general, than using Stream mode is the deployment of Promise 
a better choice.
View Code

 

Promise receiving a constructor parameter (this parameter is a function), and the two arguments: resolve, reject respectively, after the successful implementation of the callback function asynchronous operation
callbacks and post asynchronous execution failure. In fact, here with a 'success', 'failure' is not accurate to describe, in accordance with the standard terms, resolve the status is set to Promise of fullfiled
Reject state is set Promise is rejected.

01, the basic usage
ES6 predetermined, Promise object is a constructor to generate instances Promise

 

The basic structure of Promise 

Step by step load caused callback hell

    / *   // This will cause the loading step by step callback hell 
     var IMG = new new Image (); 
      img.src = "./ IMG /. 3-.jpg"; 
      img.onload = function () { 
           var = new new IMG Image (); 
           img.src = "./ IMG / 4- / JPG"; 
           img.onload = function () { 
              var IMG = new new Image (); 
              img.src = "./ IMG / 5- / JPG"; 
              IMG = function .onload () { 
                  var IMG = new new Image (); 
                  img.src = "./ IMG / 6- / JPG"; 
           } 
           } 
      } * /

 

basic structure:

/ * Var = new new Promise Promise (function (Resolve, Reject) { 
        var IMG = new new Image (); 
        img.src = "./img/3-.jpg"; 
        img.onload = function () { 
            // load successfully , resolve (this) parameters passed the this 
            Resolve (the this); 
        }; 
        img.onerror = function () { 
            // load failure 
            Reject ( "fail to load"); 
        } 
    }); 
    // This is an example of a promise, but also direct .then () connected 
    promise.then (function (Data) { 
        the console.log (Data, "__________"); 
    }, function (error) { 
        the console.log (error, "========" ); 
    }) * /
function loadImg(src) {
        return new Promise(function (res, rej) {
            var img = new Image();
            img.onload = function () {
                res(this);
            };
            img.onerror = function () {
                rej("加载错误");
            };
            img.src = src;
        });
    }

    var arr = [];
    loadImg("./img/3-.jpg").then(function (data) {
        arr.push(data);
        return loadImg("./img/4-.jpg");
    }, function (error) {
        console.log(error);
    }).then(function (data) {
        console.log(data);      //<img src='./img/4-.jpg'>
        arr.push(data);
        console.log('arr===>',arr);
    }, function (error) {
        console.log(error);
    })
Sheets of Load picture

Asynchronous Load picture

function the getImage (the src) {
             return  new new Promise ( function (RES, REJ) { 
                the let IMG = new new Image (); 
                img.src = the src; 
                img.onload = function () {
                     // loaded successfully 
                    RES (IMG); 
                }; 
                img.onerror = function () {
                     // loading error 
                    REJ ( "loading error" ) 
                } 
            }) 
        }

 Instantiate an object

/*let promise=getImage("./img/3-.jpg");
        let promise1=promise.then(res => {
            console.log(this);
            console.log('res--->',res);
            return getImage("./img/4-.jpg");
        },rej=> {
            console.log(rej);
        });
        let promise2=promise1.then(res=> {
            console.log(this);
            console.log(res);
            return getImage("./img/5-.jpg")
        });
        let promise3=promise2.then(res=> {
            console.log(this);
            console.log(res);
            return getImage("./img/6-.jpg")
        });*/

Chain asynchronous

/*
        *  链式异步
        *
        * */
        /*getImage("./img/3-.jpg").then(function (data) {
            console.log(this);
            console.log(data);
            return getImage("./img/4-.jpg");
        }).then(res=> {
            console.log(this);
            console.log(res);
            return getImage("./img/5-.jpg");
        }).then(function (data) {
            console.log(this);
            return getImage("./img/6-.jpg")
        })*/

 .then(res=>{},rej=>{})

/ *   The then there are two parameters, is a function, the first function call is successful function, the second function is a function call fails 
              getImage ( "./ img / 1- .jpg"). Then (function (data) { 
                  the console.log (Data); 
              }, function (ERR) { 
                  the console.log (ERR); 
              }) * / 
        //   the catch: the implementation of the method after the failure, there is a parameter, the parameter is a function, performed after the failure 
        / * the getImage ( "./img/1-.jpg").then(function (Data) { 
             the console.log (Data); 
         }) the catch (function (ERR) {. 
             the console.log (ERR); 
         }) * /

Promise.all

/ * 
        * Promise.all   perform multiple asynchronous array. Successfully return all the results of an array consisting of a list, failed when the value of the first to be reject a failed state is returned. 
        * 
        * * / 
        The let List = [];
         for (I = the let. 3; I <80; I ++ ) { 
            list.push (the getImage ( "./img/" + I + "-.jpg" )); 
        } 
        
       / * Promise.all (List) .then (function (ARR) { 
           the console.log (ARR); 
           arr.forEach (T => the console.log (t.src)); 
       }); * /

Promise.race

/ * 
        *    Race   race 
        * performing a plurality of asynchronous array, the first to complete asynchronous, who returns 
        * 
        * 
        * * / 

        Promise.race (List) .then ( function (Data) { 
            the console.log (Data); 
        })

 

Micro-channel micro-channel asynchronous calls applet Maps API

 

<!--form表单-->
<form bindsubmit="formSubmit">
    <!--输入起点和终点经纬度坐标,格式为string格式-->
    <label>起点坐标:
      <input style="border:1px solid #000;" name="start" value="鼓楼"></input>
    </label>
    <!--多个终点位置示例:39.984060,116.307520;39.984060,116.507520-->
    <label>终点坐标:
      <input style="border:1px solid #000;" name="dest"value="火车站"></input>
    </label>
    <!--提交表单数据-->
    <button form-type="submit">计算距离</button>
</form>

<!--渲染起点经纬度到终点经纬度距离,单位为米-->
<view wx:for="{{distance}}" wx:key="index">
    <view>起点到终点{{index+1}}的步行距离为{{item}}米</view>
</view>
map-distance.wxml

 

import myPromise from '../../utils/myPromise.js'
import calculatePromise from '../../utils/calculatePromise.js'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    distance: [],
    startPos:{},
    destPos:{}
  },

  //在Page({})中使用下列代码
  //事件触发,调用接口
  formSubmit(e) {
    //将输入的地名转化为经纬度
    const startPlace = e.detail.value.start
    const destPlace = e.detail.value.dest
    
    myPromise({addr:startPlace}).then(res=>{
      console.log(res)
      this.setData({
        startPos: res.result.location
      })
    }).then(
      myPromise({ addr: destPlace }).then(res => {
        console.log(res)
        this.setData({
          destPos: res.result.location
        })
      })
    ).then(res2 => {
      console.log('===>', this.data)
      const newStartPos = `${this.data.startPos.lat},${this.data.startPos.lng}`
      const newDestPos = `${this.data.destPos.lat},${this.data.destPos.lng}`
      console.log(newStartPos,newDestPos)
      calculatePromise({ start: newStartPos, dest: newDestPos }).then(res => { //成功后的回调
          console.log('计算距离的成功回调::', res);
          var res = res.result;
          var dis = [];
          for (var i = 0; i < res.elements.length; i++) {
            dis.push(res.elements[i].distance); //将返回数据存入dis数组,
          }
          this.setData({ //设置并更新distance数据
            distance: dis
          });
        }
      )
    })
    
    
  }


})
mao-distance.js

 

 

// 引入SDK核心类
var QQMapWX = require('../libs/qqmap-wx-jssdk.js');

// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: '2BJBZ-TKDRU-NVMV4-2JAJC-VK2Y2-M7F3D' // 必填
});

export default function calculatePromise(options) {
  return new Promise((resolve, reject) => {
      //调用距离计算接口
      qqmapsdk.calculateDistance({
        //mode: 'driving',//可选值:'driving'(驾车)、'walking'(步行),不填默认:'walking',可不填
        //from参数不填默认当前地址
        //获取表单提交的经纬度并设置from和to参数(示例为string格式)
        from: options.start || '', //若起点有数据则采用起点坐标,若为空默认当前地址
        to: options.dest, //终点坐标
        success: resolve,
        fail:reject
      });
  })
}
calculatePromise.js
// 引入SDK核心类
var QQMapWX = require('../libs/qqmap-wx-jssdk.js');

// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: '2BJBZ-TKDRU-NVMV4-2JAJC-VK2Y2-M7F3D' // 必填
});

export default function myPromise(options) {
  return new Promise((resolve, reject) => {
    //解析地名 并转化为经纬度
    qqmapsdk.search({
      keyword: options.addr,
      success: res1 => {
        console.log('地名查询--->', res1);
        const address = res1.data[0].address

        qqmapsdk.geocoder({
          address: address,
          success: resolve,
          fail: reject
        })
      }
    })
  })
}
myPromise.js

 

Guess you like

Origin www.cnblogs.com/XJT2018/p/11261089.html