这是我的第一个使用AWS API网关的应用,当我在componentDidMount中调用该函数时,我能够提取数据。

componentDidMount (){
  // debugger
  this.setState({apiData: apiCall(this.state.testSearch) })
this.updateAPIdata()

}


和apiCall是Methods.js中的函数

const apiCall = function(searchInput) {
  const searchTerm = searchInput
  var apigClientFactory = require('aws-api-gateway-client').default;

  const config =  {
                apiKey: 'xxxxxx',
                invokeUrl:'https://xxxx.execute-api.us-east-2.amazonaws.com'
                }

  var apigClient = apigClientFactory.newClient(config);
  var params = {
        //This is where any header, path, or querystring request params go. The key is the parameter named as defined in the API
        //  userId: '1234',
        search_keyword: 'Ambassador'
      };
      // Template syntax follows url-template https://www.npmjs.com/package/url-template
  var pathTemplate = '/beta/testDB'
  var method = 'GET';
  var additionalParams = {
      //If there are any unmodeled query parameters or headers that need to be sent with the request you can add them here
      headers: {

            },
      queryParams: {
        search_keyword: 'Ambassador'
              }
    }
debugger
    apigClient.invokeApi(params, pathTemplate, method, additionalParams)
             .then(function(result)
                {
                    //This is where you would put a success callback
                    return JSON.parse(result.data)

                }).catch( function(result){
                    //This is where you would put an error callback
                })
}


当我调试代码时,所有正确的变量都传递给apigClient.invokeApi,但它从未传递给then函数,它只是跳转到apiCall函数的最后一个}。这是出乎意料的,因为它将像then(function(result))那样调试下一个。

我是在调用函数错误还是其他新手错误?当它与componentDidMount位于同一.js文件中时,此代码有效。

最佳答案

问题在于,只有在解决了来自API的响应之后才返回结果,这是异步发生的。

有两种方法可以解决此问题


使用回调


`

componentDidMount() {
  apiCall(this.state.testSearch, (data, error) => {
    if (error) {
      //handle
      console.log(error)
      return
    }
    this.setState({apiData: data})
    this.updateAPIdata()
  }
}

const apiCall = function(searchInput, callback) {
  //...Your code
  apigClient.invokeApi(params, pathTemplate, method, additionalParams)
    .then((result) => {
      callback(JSON.parse(result.data))
    })
    .catch((error) => {
      callback(null, error)
    })
}



使用异步等待(我的偏好)


`

async componentDidMount() {
  try {
    const data = await apiCall(this.state.testSearch)
    this.setState({apiData: data})
    this.updateAPIdata()
  } catch(e) {
    //Handle error
  }
 }

 async function apiCall(searchInput) {
   //...Your code
   const result = await apigClient.invokeApi(params, pathTemplate, method, additionalParams)
   return JSON.parse(result)
 }

07-27 19:39