关于前端:JS循环中使用asyncawait的正确姿势

21次阅读

共计 2095 个字符,预计需要花费 6 分钟才能阅读完成。

概览(循环形式 – 罕用)

for
map
forEach
filter

申明遍历的数组和异步办法

申明一个数组:⬇️

const skills = [‘js’, ‘vue’, ‘node’, ‘react’]
复制代码

再申明一个 promise 的异步代码: ⬇️

function getSkillPromise (value) {
return new Promise((resolve, reject) => {

setTimeout(() => {resolve(value)
}, 1000)

})
}
复制代码
for 循环中应用

因为 for 循环并非函数,而 async、await 须要在函数中应用,因而须要在 for 循环外套一层 function

async function test () {
for (let i = 0; i < skills.length; i++) {

const skill = skills[i]
const res = await getSkillPromise(skill)
console.log(res)

}
}

test() // 调用
复制代码

当应用 await 时,心愿 JavaScript 暂停执行,直到期待 promise 返回处理结果。上述后果意味着 for 循环中有异步代码,是能够等到 for 循环中异步代码齐全跑完之后再执行 for 循环前面的代码。
然而他不能解决回调的循环,如 forEach、map、filter 等,上面具体分析。

map 中应用

在 map 中应用 await, map 的返回值始是 promise 数组,这是因为异步函数总是返回 promise。

async function test () {
console.log(‘start’)
const res = skills.map(async item => {

return await getSkillPromise(item)

})
console.log(res)
console.log(‘end’)
}

test()
复制代码

后果:始终为 promise 数组

start
[
Promise {<pending>},
Promise {<pending>},
Promise {<pending>},
Promise {<pending>}
]
end
复制代码

若果你想要等到 promise 的返回后果,能够应用 promise.all()解决一下

async function test () {
console.log(‘start’)
const res = skills.map(async item => {

return await getSkillPromise(item)

})
const resPromise = await Promise.all(res)
console.log(resPromise)
console.log(‘end’)
}

test()

// 后果
start
[‘js’, ‘vue’, ‘node’, ‘react’]
end

复制代码
forEach 中应用

先上代码和后果

async function test () {
console.log(‘start’)
skills.forEach(async item => {

const res = await getSkillPromise(item)
console.log(res)

})
console.log(‘end’)
}

test()
复制代码

预期后果

‘Start’
‘js’
‘vue’
‘node’
‘react’
‘End’
复制代码

理论后果 在 forEach 循环期待异步后果返回之前就执行了 console.log(‘end’)

‘Start’
‘End’
‘js’
‘vue’
‘node’
‘react’
复制代码

JavaScript 中的 forEach 不反对 promise 感知,也反对 async 和 await,所以不能在 forEach 应用 await。

filter 中应用

应用 filter 过滤 item 为 vue 或者 react 的选项

失常应用 filter:

async function test () {
console.log(‘start’)
const res = skills.filter(item => {

return ['vue', 'react'].includes(item)

})
console.log(res)
console.log(‘end’)
}

test() // 调用

// 后果
start
[‘vue’, ‘react’]
end
复制代码

应用 await 后:

async function test () {
console.log(‘start’)
const res = skills.filter(async item => {

const skill = await getSkillPromise(item)
return ['vue', 'react'].includes(item)

})
console.log(res)
console.log(‘end’)
}

test()
复制代码

预期后果:

start
[‘vue’, ‘react’]
end
复制代码

理论后果:

[‘js’, ‘vue’, ‘node’, ‘react’]
end
复制代码

论断:因为异步函数 getSkillPromise 返回后果返回的 promise 总是真的,所以所有选项都通过了过滤作者:毕了业就退休

正文完
 0