最简用 promise
let res = function () { return new Promise((resolve, reject) => { // 返回一个promise setTimeout(() => { resolve(10) }, 3000) }) } res().then(x => { // promise.then() let a = 20; a += x console.log(a); })
多个异步用 async
let res = function () { return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(10) },3000) }) } async function test(){ console.log(‘before‘); // 按顺序输出 before b after let b=await res() // 可以按顺序执行多个 promise b+=30; console.log(‘b‘,b); console.log(‘after‘); } test();
async 返回 promise (直接在async函数里面操作就行了,不要再返回了)
let res = function () { return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(10) },3000) }) } async function test(){ let b=await res() console.log(‘b‘,b); b+=30; return b; // async 返回一个 promise } let cc=0 test().then(x=>{ // promise then cc=x; console.log(‘cc‘,cc); })
async try.. catch..
let res = function (val) { return new Promise((resolve, reject) => { setTimeout(() => { if (val > 3) { resolve(10) } else { reject(false) } }, 3000) }) } async function test (val) { try { let b = await res(val) b+=20; console.log(‘b‘,b); } catch (e) { // promise有 reject时 要 try()catch{} if (e) { console.log(‘b is true‘); }else{ console.log(‘b is false‘); } } } test(10);
promise try-catch
let res = function (val) { return new Promise((resolve, reject) => { // 返回一个promise setTimeout(() => { if (val > 10) { resolve(10) }else{ reject(‘no4‘) } }, 3000) }) } res(1).then(x => { // promise.then() let a = 20; a += x console.log(a); }).catch(e=>{ if(e===‘no‘){ console.log(‘hahaha‘); }else{ console.log(‘no input‘); } })
传统回调函数
let f = function (test) { // 传入一个函数 setTimeout(()=>{ let a = 10 test(a) // 把结果给一个函数 },3000) } f(function (val) { console.log(val); // 10 })