将Async与.then一起使用

时间:2019-07-08 18:13:00

标签: javascript reactjs react-native async-await

您好,在设置了一个简单的异步函数后,用promise返回,我想使用then promise而不是try! 但是回来了

  

await是保留字

第二次等待该功能。

我试图将异步返回承诺数据放到这里!但也没有用

async infiniteNotification(page = 1) {
    let page = this.state.page;
    console.log("^^^^^", page);
    let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
    fetch(`/notifications?page=${page}`, {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Access: auth_token
      },
      params: { page }
    })
      .then(data => data.json())
      .then(data => {

        var allData = this.state.notifications.concat(data.notifications);
        this.setState({
          notifications: allData,
          page: this.state.page + 1,

        });
        let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
          fetch("/notifications/mark_as_read", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Access: auth_token
          },
          body: JSON.stringify({
            notification: {
              read: true
            }
          })
        }).then(response => {
          this.props.changeNotifications();
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

>等待是保留字(100:25) 让auth_token =等待AsyncStorage.getItem(AUTH_TOKEN);                   ^ fetch(“ / notifications / mark_as_read”,{

1 个答案:

答案 0 :(得分:2)

您应该重构您的请求方式。我将具有一个通用功能来处理设置请求和所有操作。

const makeRequest = async (url, options, auth_token) => {
  try {

    // Default options and request method
    if (!options) options = {}
    options.method = options.method || 'GET'

    // always pass a body through, handle the payload here
    if (options.body && (options.method === 'POST' || options.method === 'PUT')) {
      options.body = JSON.stringify(options.body)
    } else if (options.body) {
      url = appendQueryString(url, options.body)
      delete options.body
    }

    // setup headers
    if (!options.headers) options.headers = {}
    const headers = new Headers()
    for(const key of Object.keys(options.headers)) {
      headers.append(key, (options.headers as any)[key])
    }

    if (auth_token) {
      headers.append('Access', auth_token)
    }
    headers.append('Accept', 'application/json')
    headers.append('Content-Type', 'application/json')

    options.headers = headers

    const response = await fetch(url, options as any)
    const json = await response.json()
    if (!response.ok) {
      throw json
    }
    return json
  } catch (e) {
    console.error(e)
    throw e
  }
}

appendQueryString是一个辅助工具,用于在网址中获取get qs参数

const appendQueryString = (urlPath, params) => {
  const searchParams = new URLSearchParams()
  for (const key of Object.keys(params)) {
    searchParams.append(key, params[key])
  }
  return `${urlPath}?${searchParams.toString()}`
}

现在,要了解如何更新代码,您会发现事情变得不再那么冗长,而变得更加广泛。

async infiniteNotification(page = 1) {
  try {
    let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
    const data = await makeRequest(
      `/notifications`,
      { body: { page } },
      auth_token
    )
    var allData = this.state.notifications.concat(data.notifications);
    this.setState({
      notifications: allData,
      page: this.state.page + 1,
    });
    const markedAsReadResponse = makeRequest(
      "/notifications/mark_as_read",
      {
        method: "POST",
        body: {
          notification: { read: true }
        },
      auth_token
    )
    this.props.changeNotifications();
  } catch (e) {
    // TODO handle your errors
  }
}