所向披靡的async/await

news/2024/7/19 15:59:29 标签: js, javascript, promise, async, await

使用规则

凡是在前面添加了async的函数在执行后都会自动返回一个Promise对象

注意重点: 返回结果为Promise

javascript">async function test() { 
    return 100; 
}
console.log(test())  // Promise {<resolved>: 100}
await必须在async函数里使用,不能单独使用

async function test() {
    let result = await Promise.resolve('success')
    console.log(result)
}
test()

await后面需要跟Promise对象,不然就没有意义,而且await后面的Promise对象不必写then,因为await的作用之一就是获取后面Promise对象成功状态传递出来的参数。

javascript">function fn() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('success')
        })
    })
}
async function test() {
    let result = await fn() //因为fn会返回一个Promise对象
    console.log(result)     //这里会打出Promise成功后传递过来的'success'
}
test()

同步与异步

async函数中使用await,那么await这里的代码就会变成同步的了,意思就是说只有等await后面的Promise执行完成得到结果才会继续下去await就是等待,这样虽然避免了异步,但是它也会阻塞代码,所以使用的时候要考虑周全。

javascript">function fn(name) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(`${name}成功`)
        }, 1000)
    })
}
async function test() {
    let p1 = await fn('小红')
    let p2 = await fn('小明')
    let p3 = await fn('小华')
    return [p1, p2, p3]
}
test().then(result => {
    console.log(result)
}).catch(result => {
    console.log(result)     // 错误的处理方法,前提是函数调用,否则往下看
})

这样写虽然是可以的,但是这里await会阻塞代码,每个await都必须等后面的fn()执行完成才会执行下一行代码,所以test函数执行需要3秒。如果不是遇到特定的场景,最好还是不要这样用。

优雅的错误处理方法

一般情况下async/await在错误处理方面,主要使用 try/catch,像这样

javascript">const fetchData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('fetch data is me')
        }, 1000)
    })
}

(async () => {
    try {
        const data = await fetchData()
        console.log('data is ->', data)
    } catch(err) {
        console.log('err is ->', err)
    }
})()

asyncawait_83">一个适合使用async/await的业务场景

在前端编程中,我们偶尔会遇到这样一个场景:我们需要发送多个请求,而后面请求的发送总是需要依赖上一个请求返回的数据。

对于这个问题,我们既可以用的Promise的链式调用来解决,也可以用async/await来解决,然而后者会更简洁些。

使用Promise链式调用来处理:

javascript">function request(time) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(time)
        }, time)
    })
}
request(500).then(result => {
    console.log(result)         // 500
    return request(result + 1000)
}).then(result => { 
    console.log(result)         // 1500
    return request(result + 1000)
}).then(result => {
    console.log(result)         // 2500
}).catch(error => {
    console.log(error)
})

asyncawait_111">使用async/await的来处理:

javascript">function request(time) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(time)
        }, time)
    })
}
async function getResult() {
    let p1 = await request(500)
    let p2 = await request(p1 + 1000)
    let p3 = await request(p2 + 1000)
    return p3
}
getResult().then(result => {
    console.log(result) // 2500
}).catch(error => {
    console.log(error)
})

相对于使用then不停地进行链式调用, 使用async/await会显的更加易读一些。

await_135">在循环中使用await

如果在是循环中使用await,就需要牢记一条:必须在async函数中使用。

javascript">let times = [1000, 500, 2000]
async function test() {
    let result = []
    for (let item of times) {
        let temp = await request(item)
        result.push(temp)
    }
    return result
}
test().then(result => {
    console.log(result)
}).catch(error => {
    console.log(error)
})

测试

javascript">console.log(1)
let promiseDemo = new Promise((resolve, reject) => {
    console.log(2)
    setTimeout(() => {
        let random = Math.random()
        if (random >= 0.2) {
            resolve('success')
            console.log(3)
        } else {
            reject('failed')
            console.log(3)
        }   
    }, 1000)
})
console.log(8)
async function test() {
    console.log(4)
    let result = await promiseDemo
    return result
}
setTimeout(() => {
    console.log(7)
}, 0)
test().then(result => {
    console.log(5)
}).catch((result) => {
    console.log(5)
})

console.log(6)

// 1 2 8 4 6 7 3 5

http://www.niftyadmin.cn/n/658233.html

相关文章

个税起征点升高----节省了多少?

个税起征点今年一月开始执行&#xff0c;大家大多可以节省不小的支出。可惜我的收入低&#xff0c;只节省了将近&#xff11;&#xff10;&#xff10;元。大家都节省多少&#xff1f;&#xff1f;&#xff1f;&#xff1f;&#xff1f;&#xff1f;

fedora 国内源

wget http://mirrors.163.com/.help/fedora-163.repowget http://mirrors.163.com/.help/fedora-updates-163.repo 转载于:https://www.cnblogs.com/wangjq19920210/p/10694800.html

BZOJ2007: [Noi2010]海拔

BZOJ2007: [Noi2010]海拔 Description YT市是一个规划良好的城市&#xff0c;城市被东西向和南北向的主干道划分为nn个区域。简单起见&#xff0c;可以将YT市看作一个正方形&#xff0c;每一个区域也可看作一个正方形。从而&#xff0c;YT城市中包括(n1)(n1)个交叉路口和2n(n1)…

instanceOf 运算符原理

定义 instanceof运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置。 —— MDN 简单理解为&#xff1a;instanceof可以检测一个实例是否属于某种类型。 function Foo(){} const a new Foo()a instanceof Foo // true a instanceof Object /…

ElasticSearch文档及分布式文档存储

1、什么是文档&#xff1f; 文档由索引&#xff08;_index&#xff09;,类型&#xff08;_type&#xff09;,唯一标识(_id) 组成&#xff0c;我们为 _index(索引) 分配相关逻辑地址分片&#xff0c;该索引下的数据会根据索引以及类型计算哈希来分配数据存储的分片&#xff0c;文…

update from 语句的写法

UPDATE EPD_ITEM_MASTER rrSET plan_price (SELECT top 1 plan_price FROM newdata WHERE item_code rr.item_code)WHERE item_code IN (SELECT item_code from uuu) 我有三个表 epd_item_master,newdata,uuu我是想用newdata中的plan_price 代替 epd_item_master中的 plan_pr…

[C++_QT] Error: Not a signal or slot declaration

问题: 在Qt工程中添加了一个新的窗口之后 一直报错 如下 单单从错误描述上看 是缺少信号或者槽 但是我确定没有缺少啊 然后第二个错误显示了一个mox_xxxx文件 然后我就去那个目录下去找那个文件 但是发现没有 所以接下来就是找到为什么没有moc_xxx文件 moc文件的生成和 有关系 …

浏览器输入URL后都发生了什么??

DNS 域名解析 在网络世界&#xff0c;你肯定记得住网站的名称&#xff0c;但是很难记住网站的 IP 地址&#xff0c;因而也需要一个地址簿&#xff0c;就是 DNS 服务器。DNS 服务器是高可用、高并发和分布式的&#xff0c;它是树状结构&#xff0c;如图&#xff1a; 根 DNS 服…