Javascript中promise,async和await的区别是什么

发布时间:2022-03-24 09:13:19 作者:iii
来源:亿速云 阅读:181

本文小编为大家详细介绍“Javascript中promise,async和await的区别是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“Javascript中promise,async和await的区别是什么”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

终于把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)
     })
}

读到这里,这篇“Javascript中promise,async和await的区别是什么”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. Async/Await替代Promise的6个理由
  2. JS的Promise和Async是什么?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript promise async

上一篇:Vue的核心原理是什么

下一篇:Vue3中toRef与toRefs的区别是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》