我有一个带有动画功能的react-native应用程序,我正在尝试创建一个动画助手功能,该功能在继续执行并将值返回给动画功能之前,等待在另一个屏幕上解析该值。
动画助手功能取决于用户在另一个屏幕上购买或不购买订阅的结果,我向第二个屏幕传递了一个承诺,以解决用户是否购买订阅的问题。在兑现这一诺言之后,我然后要继续执行我的第一个动画助手功能,并返回用户是否购买了我的第一个动画功能的订阅的值。
这是我的动画功能
Animated.timing(position, {
toValue: {x: width, y: 0},
duration: 300,
}).start(async() => {
const touchJustAdded = await animationHelper({props})
this.setState({touchJustAdded: actionAllowed}) //This should update the state with the value returned from the animation helper before continuing animation.
//touchJustAdded is used in another function to control the text shown in the animated view, so I need the value to be set here before continuing the animation. I also don't want to continue the animation until the user returns from the BuySubscription screen.
Animated.timing(position, {
toValue: {x: 0, y: 0},
delay: 1200,
duration: 300,
})
})
这是我的动画助手功能
const AnimationHelper = async ({props}) => {
//check if user has a subscription or other conditions are met, do stuff, then return true. Otherwise, navigate to BuySubscription screen
navigation.navigate('BuySubscription',{promiseCallback})
//I want to pause execution here until the promiseCallback promise is resolved
return subscriptionBought //I need to wait for the user to complete their action on the other screen and then somehow return the value to the animationHelper before returning here
}
这是我创造诺言的方式:
promiseCallback = async (subscriptionBought) => {
return new Promise((resolve,reject) => {
resolve( subscriptionBought)
})
}
当用户离开该屏幕时,将使用以下代码在BuySubscription屏幕中解决该承诺:
this.props.navigation.state.params
.promiseCallback(this.state.subscriptionBought)
在继续AnimationHelper之前,我要等待诺言得到解决。
感谢您的帮助!我已经搜索过,但是我不了解如何在不调用它的情况下在Animation函数中等待promiseCallback。
答案 0 :(得分:0)
尝试
const functionToAwait = async ({props}) => {
let hold = await promiseCallback();
if(hold){
navigation.navigate('BuySubscription',hold)
//I want to pause execution here until the promiseCallback promise is resolved
return
}
}
答案 1 :(得分:0)
您还必须await
履行承诺function
。并且还必须等待调用promise函数的位置。
e.g.
promiseCallback = async (subscriptionBought) => {
return await new Promise((resolve,reject) => {
resolve( subscriptionBought)
})
}
答案 2 :(得分:0)
您可以不做这样的承诺:
Screen1:
promiseCallback = (subscriptionBought) => {
alert("Result: " + subscriptionBought)
// continue your animation here
}
const Animation = async ({props}) => {
//start animation
navigation.navigate('BuySubscription', {promiseCallback: this.promiseCallback})
return
}
现在在BuySubscription
个事件的promiseCallback
屏幕调用componentWillUnmount
中>
componentWillUnmount() {
this.props.navigation.state.params.promiseCallback(this.state.subscriptionBought);
}