javascript - 将异步 es6 语法函数转换为 es5 语法异步函数
问题描述
我正在使用一个包,我正在将该包的函数定义(https://github.com/3DJakob/react-tinder-card/blob/master/index.js)转换回 es5 语法,但是,我无法转换 animateOut 函数,因为它是一个异步函数:
const animateOut = async (element, speed, easeIn = false) => {
const startPos = getTranslate(element)
const bodySize = getElementSize(document.body)
const diagonal = pythagoras(bodySize.x, bodySize.y)
const velocity = pythagoras(speed.x, speed.y)
const time = diagonal / velocity
const multiplier = diagonal / velocity
const translateString = translationString(speed.x * multiplier + startPos.x, -speed.y * multiplier + startPos.y)
let rotateString = ''
const rotationPower = 200
if (easeIn) {
element.style.transition = 'ease ' + time + 's'
} else {
element.style.transition = 'ease-out ' + time + 's'
}
if (getRotation(element) === 0) {
rotateString = rotationString((Math.random() - 0.5) * rotationPower)
} else if (getRotation(element) > 0) {
rotateString = rotationString((Math.random()) * rotationPower / 2 + getRotation(element))
} else {
rotateString = rotationString((Math.random() - 1) * rotationPower / 2 + getRotation(element))
}
element.style.transform = translateString + rotateString
await sleep(time * 1000)
}
有人能帮我吗?谢谢!
解决方案
本质上,您需要将任何await
s 扩展为承诺,并确保animateOut
也将 s 与.then()
而不是await
:
var animateOut = function(element, speed, easeIn) {
easeIn = easeIn || false;
// animateOut code here
return sleep(1000).then(function() {
console.log('Already slept, done.')
})
}
animateOut().then(function() {
console.log('Done animating out')
})
function sleep(time) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve();
}, time)
})
}
推荐阅读
- unity3d - 在 Unity 中的纹理中创建边界框
- r - 如何在 ggplot2 中为多个图层添加自定义图例?
- kubernetes - 为什么 Kubernetes 部署不支持服务?
- python - 如何优化此 Asyncio 代码片段以在突发周期内每秒发出更多请求?
- c# - Xamarin C# - 在 TabbedPage 中使用导航页或 ListView
- hadoop - 如果未在 hdfs-site.xml 中定义,namenode 和 datanode 将安装在哪里?
- java - hystrix HealthCounts getTotalRequests 结果似乎错误
- ios - 如何在 iOS Swift 中处理多个 UISlider 值?
- sql - CDC 由于隐式转换而失败...如何找到它?
- python - 蟒蛇中的biopython,而不是jupyter笔记本