首页 > 解决方案 > 如何从承诺中获取数据?

问题描述

我是新的承诺,并且被卡住了。我想在最后获取数据,并返回一个承诺,因为我正在编写一个函数,我将在某些情况下使用它并对返回的数据做不同的事情。

我想按.then((user) => Promise.resolve({ user, userObject }))原样返回 LAST ,以便在我将使用函数的地方与 then 一起使用它,但现在我不会以该语句结束,以防我在第一个 .then 语句中丢失数据。怎么了?

更新:

所以这里是完整的功能体。现在我像这样使用它:

signUpUser({ credentials: preparedForm })
  .then((t) => console.log('submitHandler -> t', t))
  .catch((e) => {
    handleSignUpErrors({
      form: signUpForm,
      updateForm: setSignUpForm,
      error: e,
      showErrors: setShowErrors,
    })
  })

但我没有得到console.log。怎么了?

const signUpUser = ({ credentials }) => {
  const {
    name,
    lastName,
    email,
    password,
    phone,
    emailVerified,
    phoneVerified,
  } = credentials

  const userObject = getUserObject({
    name,
    lastName,
    email,
    password,
    phone,
    emailVerified,
    phoneVerified,
  })

  return firebase
    .auth()
    .createUserWithEmailAndPassword(email, password)
    .then((data) =>
      db
        .collection('users')
        .doc(data.user.uid)
        .set(userObject)
        .then(() => data)
    )
    .then((user) => ({ user, userObject }))
}

标签: javascriptpromise

解决方案


const userObject = getUserObject({
  name,
  lastName,
  email,
  password,
  phone,
  emailVerified,
  phoneVerified,
})

return firebase
  .auth()
  .createUserWithEmailAndPassword(email, password)
  .then((data) =>
    db
    .collection('users')
    .doc(data.user.uid)
    .set(userObject)
    .then(response => response)
  )
  .then(result => console.log(result))

推荐阅读