import profile from './profile.mjs' // pkg. // console.log(profile.firstName, profile.lastName, profile.year) // 模拟的一次网络IO // executor: (resolve: (value: any) => void, reject: (reason?: any) => void) function testResultCallbackFunc(success, failed) { var timeOut = Math.random() * 2; console.log('set timeout to: ' + timeOut + ' seconds.'); setTimeout(function () { if (timeOut < 1) { console.log('call resolve()...'); success('200 OK'); } else { console.log('call reject()...'); failed('timeout in ' + timeOut + ' seconds.'); } }, timeOut * 1000); } // testResultCallbackFunc(data => console.log(data), err => console.log(err)) // testResultCallbackFunc(data => console.log(data), err => console.log(err)) // testResultCallbackFunc(data => console.log(data), err => console.log(err)) // JS 编程范式 // new Promise(testResultCallbackFunc).then((value) => { // console.log(value) // }).catch((err) => { // console.log(err) // }).finally(() => { // console.log('finally') // }) // new Promise(testResultCallbackFunc).then((value) => { // console.log(value) // }).catch((err) => { // console.log(err) // }).finally(() => { // console.log('finally') // }) // new Promise(testResultCallbackFunc).then((value) => { // console.log(value) // }).catch((err) => { // console.log(err) // }).finally(() => { // console.log('finally') // }) // async + await 控制异步的调用顺序,也就是同步编程 // A -> B() -> C() // set timeout to: 0.9367326782693821 seconds. // call resolve()... // set timeout to: 0.09577379370967654 seconds. // call resolve()... // set timeout to: 0.5294275808882718 seconds. // call resolve()... var bizfn = async () => { try { var a = new Promise(testResultCallbackFunc) await a var b = new Promise(testResultCallbackFunc) await b var c = new Promise(testResultCallbackFunc) await c } catch(err) { console.log(err) } // a.then(() => { // b.then(()=> { // c.then(() => { // }) // }) // }) } bizfn()