如何将可正常运行的JavaScript数组洗牌函数改写为Async异步函数
数组洗牌函数异步改造方案
最简改造版本
仅给原函数增加async关键字即可满足异步函数的要求,原有逻辑完全保留:
const src = [...'abcdefg']; const shuffle = async arr => [...arr].reduceRight((res,_,__,s) => (res.push(s.splice(0|Math.random()*s.length,1)[0]), res),[]); // 异步函数必须通过await或.then拿返回结果 (async () => { console.log(await shuffle(src)); })() // 也可以用.then调用:shuffle(src).then(res => console.log(res))
带实际异步逻辑的改造版本
如果需要匹配真实异步场景(比如使用更安全的浏览器原生异步安全随机数、加延迟模拟异步计算),可以参考如下实现:
const src = [...'abcdefg']; const shuffle = async (arr) => { const tempArr = [...arr] const shuffledRes = [] while (tempArr.length) { // 调用异步安全随机数接口,比Math.random随机性更强 const randomVal = crypto.getRandomValues(new Uint32Array(1))[0] const randomIdx = randomVal % tempArr.length shuffledRes.push(tempArr.splice(randomIdx, 1)[0]) // 如需模拟异步延迟可取消下方注释 // await new Promise(resolve => setTimeout(resolve, 50)) } return shuffledRes } // 调用 (async () => { const result = await shuffle(src) console.log(result) })()
注意事项
- 所有标记
async的函数默认返回Promise实例,直接同步调用拿到的是Pending状态的Promise,取不到计算结果 - 若内部有其他异步依赖(比如拉取远程随机种子、读写文件等),直接在函数内部对应位置加
await即可
内容的提问来源于stack exchange,提问作者Sona Shetty
相关产品推荐
相关产品推荐

