Promise 异步操作按顺序执行
方法1 ES6 promise.then
// 初始化设备 const initVpn = () => { return new Promise((resolve)=>{ setTimeout(item=>{ console.log('初始化设备成功') resolve(true) },1000) }) } // 登录 const loginVpn = () => { return new Promise((resolve)=>{ setTimeout(item=>{ console.log('登录成功') resolve(true) },1000) }) } // 获取资源 const getVpnResource = () => { return new Promise((resolve)=>{ setTimeout(item=>{ console.log('获取资源成功') resolve(true) },1000) }) } // 开启VPN const startService = () => { return new Promise((resolve)=>{ setTimeout(item=>{ console.log('开启VPN成功') resolve(true) },1000) }) } initVpn() .then(ok=>{ if(ok) return loginVpn() }) .then(ok =>{ if(ok) return getVpnResource() }).then(ok =>{ if(ok) return startService() })
方法2 ES8 async /await
const start = async () => { try { await initVpn(); await loginVpn(); await getVpnResource(); await startService(); } catch (err) { console.log( '%cerr', 'border-radius:3px;background:#000;color:#f6e387;padding: 2px 5px', err ); } }; start();
技巧:
1.多级嵌套
function A() { return new Promise(async (resolve, reject) => { const data = await B(); resolve(data); }); } const B = function () { return new Promise((resolve, reject) => { resolve({ code: 200 }); }); }; const C = async () => { const data = await A(); console.log('data', data); }; C(); // {code: 200}