【问题标题】:My javascript Async Await api request returns a strange object我的 javascript Async Await api 请求返回一个奇怪的对象
【发布时间】:2019-09-14 06:43:51
【问题描述】:

我正在使用Frisbee 发出 API 请求:

const Frisbee = require('frisbee')

const api = new Frisbee({
  baseURI: 'http://192.168.1.8:4000',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
})

export const handleSubmit = async (values): void => {
  Toast.show('Uploading Product', {
    duration: 3000,
    position: 30,
    shadow: true,
    animation: true,
    hideOnPress: true,
    delay: 0
  })

  try {
    const response = api.post('/products', {
      body: encodeAddProductAction(values)
    })
    if (response.err) throw response.err
    console.log(response)
  } catch (err) {
    console.error(err)
  }
}

export const encodeAddProductAction = (values: any) => {
  const submitPayload = Object.assign({}, values)
  Object.keys(submitPayload).forEach((key) => {
    if (key != 'Categories') {
      submitPayload[key] = encodeURIComponent(
        JSON.stringify(submitPayload[key])
      )
    } else {
      // values[key] = JSON.stringify(values[key])
      submitPayload[key] = submitPayload[key].join(',')
    }
  })

  return submitPayload
}

控制台会记录这个:

为什么我的 API 响应体隐藏在一些奇怪的字段中,例如 _55

我的回答是:

【问题讨论】:

  • 您将此命名为“异步等待问题”,但您没有使用 await。这就是它返回承诺而不是响应的原因。
  • const response = await api.post(...)
  • @Barmar 知道了。谢谢
  • @Barmar 所以这些数字来自飞盘库 40、60、55,你知道在 promise 中使用这些特定数字的原因是什么吗?
  • 不知道,这只是一些你不需要担心的内部数据。

标签: javascript react-native async-await


【解决方案1】:

您正在使用async,但您不是awaiting 响应,这就是您返回Promise 的原因。

 try {
    const response = await api.post('/products', {
      body: encodeAddProductAction(values)
    })
    if (response.err) throw response.err
    console.log(response)
  } catch (err) {
    console.error(err)
  }

Async 默认返回Promise

【讨论】:

  • 谢谢。在允许的情况下接受。
猜你喜欢
  • 1970-01-01
  • 2019-10-05
  • 2018-05-03
  • 2021-12-04
  • 2019-06-29
  • 2023-04-05
  • 2020-03-23
  • 1970-01-01
  • 2021-12-28
相关资源
最近更新 更多