Promise notes

import Axios from 'axios'; Export default {// Regeo (params) {return new Promise(resolve, reject) => {Axios({method: 'get', url: 'https://restapi.amap.com/v3/geocode/regeo?parameters', params: { key: '4fa3c0f2d5cced992d5d61d64b17c6ac', location: `${params.longitude},${params.latitude}`, }, }) .then((res) => { resolve(res); }) .catch((error) => { reject(error); }); }); }}; -------------------- import Amap from './src/pages/utils/amap'; Amap.regeo({longitude: '103', latitude: '30'}).then((res) => { console.log(res); });Copy the code

Promise to use

// Resolve and reject are functions, where resolve means everything is ok, reject is called when an exception occurs: New Promise(function (resolve, reject) {var a = 0; var b = 1; if (b == 0) reject("Diveide zero"); else resolve(a / b); }). Then (function (value) {// throw new Error(' something wrong '); console.log("a / b = " + value); }).catch(function (err) { console.log(err); }).finally(function () { console.log("End"); });Copy the code

Pay attention to

  • By default, the then block is executed in downward order. A return cannot be interrupted. A throw can be used to jump to a catch.

  • Resolve and reject are scoped only by initial functions, excluding THEN and other sequences. Resolve and reject do not stop the initial function, and don’t forget return.