Javascript 等待 Promise 在不同的函数中解析,然后再继续异步函数进行动画处理

Javascript Wait for Promise to be resolved in a different function before continuing async function for animation

我有一个带有动画功能的 react-native 应用程序,我正在尝试创建一个动画辅助功能,该功能等待在继续执行之前在另一个屏幕上解析值并 returning a动画功能的价值。

动画助手功能取决于用户在另一个屏幕上购买或不购买订阅的结果,我向第二个屏幕传递一个承诺,由用户是否购买订阅来解决。解决此承诺后,我想继续执行我的第一个动画辅助函数和 return 用户是否订阅了我的第一个动画函数的值。

这是我的动画函数

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 之前等待承诺被解决。

感谢任何帮助!我已经搜索过,但我不明白如何在不调用动画函数的情况下等待动画函数中的 promiseCallback。

试试这个

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
  }
}

您还必须await承诺function。并且还必须等待您调用 promise 函数的位置。

e.g.

promiseCallback = async (subscriptionBought) => {
  return await new Promise((resolve,reject) => {
    resolve( subscriptionBought)
  })
}

你可以像这样没有承诺地做:

屏幕 1:

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);
}