异步函数返回undefined

时间:2016-01-30 04:50:56

标签: javascript async-await fetch-api ecmascript-next

我正致力于从GraphQL Server获取数据,并且我试图通过babel实现ES7 Async功能。我目前正在控制台中收到undefined,而且我不确定我做错了什么。

import fetch from 'isomorphic-fetch';
/**
 * [transport creates call to server with isomorphic-fetch]
 * @param  {[String]} path        [url to hit with request]
 * @param  {[Object]} query       [The GraphQL query/mutation]
 * @param  {[Object]} queryParams = {} [Params to pass into query]
 * @return {[Promise]}            [Promise containing payload]
 */
 //function that returns a promise
 export function transport (path, query, queryParams = {}) {
     return new Promise ((resolve, reject) => {
       return fetch(path, {
             method: 'POST',
             headers: {
                 'Accept': 'application/json',
                 'content-type': 'application/json'
             },
             body: JSON.stringify({
                 query,
                 queryParams
             })
         })
         .then(res => res.json())
         .then(response => {
           if(response.errors) {
             return error(response.errors);
           }
           return resolve(response.data);
         })
         .catch(error);
     });
 }
import { transport } from './utils/transport.js';

/**
 * [reachGraphQL Makes queres or mutations against GraphQL]
 * @param  {[String]} path        [path to the GraphQL server]
 * @param  {[Object]} query       [The query that GraphQL will use to fetch your data]
 * @param  {[object]} queryParams =  {} [Should contain object with different query params]
 * @return {[Object]}             [Data that was queried or mutated]
 */
//Heres Where I'm awaiting a promise from the transport function
export function reachGraphQL (path, query, queryParams = {}) {
  async () => {
    try{
      let response = await transport(path, query, queryParams);
      return response;
    } catch (error) {
      console.log(error)
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您的reachGraphQL只定义async箭头功能,但不对其执行任何操作。而且return没有任何东西。相反,它应该是async本身:

export async function reachGraphQL (path, query, queryParams = {}) {
    try {
        return await transport(path, query, queryParams);
    } catch (error) {
        console.log(error)
    }
}