【问题标题】:Why does my async function always return false to the wrapper function?为什么我的异步函数总是向包装函数返回 false?
【发布时间】:2021-09-05 11:59:09
【问题描述】:

我有一个异步函数触发 AWS Amplify 向用户发送密码重置代码。

export async function forgotPassword(username) {
  console.log('forgotPassword')
  return Auth.forgotPassword(username)
    .then(data => {
      console.log('aws reset password request success')
      console.log(data)
    })
    .catch(error => {
      console.log('error with call to AWS forgotPassword fncn')
    })
}

这是一个包装函数,它调用了上面的函数……

  forgotPassword(email).then(success => {
    if (success) {
      console.log('successful forgot password action')
      Vue.prototype.$notification.success({
        message: 'Forgot password action success',
        description: 'You have successfully submitted a password refresh request!',
      })
    }
    if (!success) {
      console.log('failed forgot password action')
    }
  })

我知道内部函数运行成功,因为用于调试该方法的控制台日志语句确实执行并打印了'aws reset password request success'

但是,我的包装函数总是检测到 aws 函数中的故障,因为我看到包装函数进入了 !success 子句。为什么是这样?我猜我的内部 aws 函数中的异步等待代码存在语法错误


更新,根据我目前阅读的答案,我更新了我的内部函数如下。

export async function forgotPassword(username) {
  console.log('forgotPassword')
  try {
    const data = await Auth.forgotPassword(username)
    console.log('aws password reset request success')
    console.log(data)
    return true
  } catch (error) {
    console.log('error with call to AWS forgotPassword fncn')
    notification.warning({
      message: error.code,
      description: error.message,
    })
  }
}

它似乎工作正常。

【问题讨论】:

  • 你的函数中没有return true(在.then内)所以它什么也不返回,即undefined,这是假的。
  • 顺便说一句,你定义了你的函数async,但你没有使用它。如果您使用await 而不是使用.then(并使用try/catch 而不是.catch),那么它也不会那么混乱
  • 经验法则:没有awaitasync 是没用的。将asyncawait 一起使用,或者不要使用async
  • 是的,现在看起来不那么混乱了,对吧? :) (你也看到我在我之前的评论中链接的例子了吗?)

标签: javascript asynchronous async-await amazon-cognito aws-amplify


【解决方案1】:

这是因为第一个函数返回的承诺解析为未定义。当您将 .then 链接到初始承诺时,您应该确保 返回 承诺应该解决:

    .then(data => {
      console.log('aws reset password request success')
      console.log(data)
      return data; // or: return true;
    })

【讨论】:

  • 这意味着 catch 应该返回 false,对吗?我也在学习=)
  • 是的,如果你愿意的话。默认值为undefined,它是“假的”,所以if (!success) 也可以使用它。注意:OP 应该将 if 设为 else
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 2021-08-01
  • 2019-05-20
  • 1970-01-01
  • 2017-09-24
  • 2020-01-11
  • 1970-01-01
相关资源
最近更新 更多