时间:2022-09-27 11:11:12 | 栏目:JavaScript代码 | 点击:次
终于把promise, async, await的区别和联系弄清楚了,看下面代码
写法1,2是promise的写法
写法6是async和await的写法
主要看第2种写法和第6中写法即可, 第2种写法是promise的典型写法,第6中写法是async, await的典型写法
// 以下三个请求依次执行 req1 = () => { return fetch("http://example.com/api/v1/get")} req2 = () => { return fetch("http://example.com/api/v1/post")} req3 = () => { return fetch("http://example.com/api/v1/delete")} //写法1 req1().then(res=>{ console.log("1: ",res) req2().then(res =>{ console.log("2: ",res) req3().then(res =>{ console.log("3: ",res) }) }) }) // 写法2 req1().then(res =>{ console.log("1: ", res) return req2() }) .then(res =>{ console.log("2: ", res) return req3() }) .then(res =>{ console.log("3: ", res) }) // 写法3 function f1(){ req1() req2() req3() } // 写法4 async function f2(){ await req1 await req2 await req3 } // 写法5 async function f3(){ req1().then(res => { console.log("1:", res) }) await f3_1() } async function f3_1(){ req1().then(res => { console.log("2:", res) }) await f3_2() } async function f3_2(){ req2().then(res=>{ console.log("3: ",res) }) } // 写法6 ff() async function ff(){ await req1_good() } async function req1_good(){ fetch("http://example.com/api/v1/get").then(res =>{ console.log("1: ",res) }) await req2_good() } async function req2_good() { fetch("http://example.com/api/v1/post").then(res =>{ console.log("2: ",res) }) await req3_good() } async function req3_good() { fetch("http://example.com/api/v1/delete").then(res => { console.log("3: ",res) }) }