将Async与.then一起使用 [英] Use Async with .then promise

查看:1318
本文介绍了将Async与.then一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hello after setup a simple async function with promise return i'd like to use then promise instead of try! But is returning

await是保留字

await is a reserved word

第二次等待该功能.

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

i've tried to place async return promise the data! but did not worked either

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",{

> await is a reserved word (100:25) let auth_token = await AsyncStorage.getItem(AUTH_TOKEN); ^ fetch("/notifications/mark_as_read", {

推荐答案

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

You should refactor how you make your requests. I would have a common function to handle setting up the request and everything.

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是一个用于在URL中获取qs参数的小助手工具

appendQueryString is a little helper util to do the get qs params in the url

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

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

Now, to get to how you update your code, you'll notice things become less verbose and more extensive.

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

这篇关于将Async与.then一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆