zoukankan      html  css  js  c++  java
  • Callback, Promise和Async/Await的对比

    Callback, PromiseAsync/Await的对比

    Callback Hell

    getData1(function (data1) {
        console.log('我得到data1了')
        
        getData2(function (data2) {
            console.log('我得到data2了')
            console.log('data1 + data2 = ...')
        })
    })
    

    Promise

    function getData1() {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve(1111)
            }, 5000)
        })
    }
    
    function getData2() {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve(2222)
            }, 10000)
        })
    }
    
    function doSomething() {
        let p1 = getData1().then(function (data) {
            console.log('请求成功: data1 = ' + data)
            return data
        })
        let p2 = getData2().then(function (data) {
            console.log('请求成功: data2 = ' + data)
            return data
        })
        Promise.all([p1, p2]).then(function (data) {
            var sum = data[0] + data[1]
            console.log('data1 + data2 = ' + sum)
        })
    }
    

    Async/Await

    async function getData1() {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve(1111)
            }, 5000)
        })
    }
    async function getData2() {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve(2222)
            }, 5000)
        })
    }
    
    async function doSomething() {
        var data1 = await getData1()
        console.log('请求成功: data1 = ' + data1)
    
        var data2 = await getData2()
        console.log('请求成功: data2 = ' + data2)
    
        var sum = data1 + data2
        console.log('data1 + data2 = ' + sum)
        
    }
    
    
  • 相关阅读:
    存储过程
    C++学习总结
    Android快速开发系列 10个常用工具类
    SimpleHttpServer的学习之总体架构
    SimpleHttpServer的学习之UML
    SimpleHttpServer的学习(1)
    map用法
    idea 中resources下于java包名相同的包不能导入XML文件问题
    leetcode621
    Yukari's Birthday 枚举+二分 过程注意数据的溢出问题 HDU4430
  • 原文地址:https://www.cnblogs.com/forzhaokang/p/8317889.html
Copyright © 2011-2022 走看看