返回值只要是 Promise, 就可用 async/await 處理異步
服務端代碼見文末ios
登陸
1.認證 獲取 token
2.用 token 獲取角色 id
3.用 token 和角色 id 獲取菜單express
new Promise(請求1) .then(請求2(請求結果1)) .then(請求3(請求結果2)) .then(請求4(請求結果3)) .then(請求5(請求結果4)) .catch(處理異常(異常信息))
直接在瀏覽器 console 可運行如下代碼json
async function login() { const baseUrl = 'http://127.0.0.1:3005'; const { token } = await fetch(`${baseUrl}/auth`, { method: 'POST', data: { username: 'test', password: 'xxxxxxx' }, }).then(v => v.json()); // 這裏後面在then一次是由於fetch直接返回的不是Promise 而是Response 而response.json()纔會返回Promise console.log('1.token->', token); const roles = await fetch(`${baseUrl}/roles?token=${token}`).then(v => v.json()); console.log('2.roles->', roles); const menus = await fetch(`${baseUrl}/menus?token=${token}&roles=${roles}`).then(v => v.json()); console.log('3.menus->', menus); }
wx.request({ url: '請求一', data: { x: '', y: '' }, header: { 'content-type': 'application/json' }, success (res) { wx.request({ url: '請求二', data: res.data, header: { 'content-type': 'application/json' }, success (res) { ...... } }) } })
1.用 Promise 封裝一個請求函數axios
const request = (url, options = { headers: {} }) => { const baseUrl = 'http://127.0.0.1:3005'; const headers = { 'content-type': 'application/json', ...options.headers, }; const method = options.method || 'GET'; const data = options.data || ''; return new Promise((resolve, reject) => { wx.request({ url: baseUrl + url, data, method, header: headers, success(res) { resolve(res); }, fali(err) { reject(err); }, }); }); };
2.業務代碼小程序
const login = async () => { const { data: { token }, } = await request('/auth', { method: 'POST', data: { username: 'test', password: 'xxxxxxx' } }); console.log('1.token->', token); const { data: roles } = await request('/roles', { data: { token } }); console.log('2.roles->', roles); const { data: menus } = await request('/menus', { data: { token, roles } }); console.log('3.menus->', menus); };
const sleep = time => { return new Promise(resolve => { console.log(`等待${time}秒...`); setTimeout(() => { resolve(true); }, time * 1000); }); };
const request = require('axios'); request.defaults.baseURL = 'http://127.0.0.1:3005'; async function login() { const { data: { token }, } = await request('/auth', { method: 'POST', data: { username: 'test', password: 'xxxxxxx' } }); console.log('1.token->', token); await sleep(2); const { data: roles } = await request('/roles', { params: { token } }); console.log('2.roles->', roles); await sleep(2); const { data: menus } = await request('/menus', { params: { roles, token } }); console.log('3.menus->', menus); }
傳統 setInterval 是每一個一段固定的時間調用一次任務,不關心任務時長,指望一個關心任務時長的 interval
const interval = async (task, time, id) => { while (true) { if (!global[id]) break; await new Promise(res => { res(task()); }); await sleep(time); } }; const addInterval = (task, time = 5) => { const id = Symbol(); global[id] = true; setTimeout(() => { interval(task, time, id); }, 0); return id; }; const delInterval = id => { global[id] = false; };
以上面的login
爲例瀏覽器
const id = addInterval(login, 2); //任務間隔2s setTiemt(() => { // 在某個時間段或者某個操做時中止循環 delInterval(id); }, xxx);
const app = require('express')(); const bodyParser = require('body-parser'); const { sleep } = require('./tools'); app.use(bodyParser.json()); app.use( bodyParser.urlencoded({ extended: true, }), ); app.all('*', function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS'); res.header('X-Powered-By', ' 3.2.1'); res.header('Content-Type', 'application/json;charset=utf-8'); next(); }); app.post('/auth', (req, res) => { const { username } = req.body; console.log(username); res.send({ id: 1, name: username, age: 18, token: `absfgsakjdhjskahdsklh`, }); }); app.post('/auth/slow', async (req, res) => { const { username } = req.body; console.log(username); await sleep(4); res.send({ id: 1, name: username, age: 18, token: `absfgsakjdhjskahdsklh`, }); }); app.get('/roles', (req, res) => { res.send([1, 2, 3]); }); app.get('/roles/slow', async (req, res) => { await sleep(4); res.send([1, 2, 3]); }); app.get('/menus', (req, res) => { res.send([ { name: '首頁', path: '/' }, { name: '用戶管理', path: '/users' }, ]); }); app.get('/slow', async (req, res) => { const second = Math.round(Math.random() * 7) + 1; await sleep(second); // res.append('Access-Control-Allow-Origin','*') res.send({ code: 0, data: Date.now(), msg: 'ok', }); }); app.listen(3005, () => { console.log(`server run time: ${Date.now()}`); });