返回未定义的异步函数
Posted
技术标签:
【中文标题】返回未定义的异步函数【英文标题】:Async Functions returning undefined 【发布时间】:2016-05-07 23:47:10 【问题描述】:我正在从 GraphQL 服务器获取数据,我正在尝试通过 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)
【问题讨论】:
你的 promise 实现了 resolve,但不会在错误时调用 reject。你的代码会吞下异常吗? 不完全确定,我认为这是我在reachGraphQL() 上使用异步的方式 “错误”在哪里定义? 对不起,我的意思是在顶部模块中 看起来如果 response.errors 是事实,你的承诺会吞下一个异常,说“错误未定义” 【参考方案1】:您的 reachGraphQL
只是定义了一个 async
箭头函数,但没有对其做任何事情。它没有return
任何东西。相反,它应该是async
本身:
export async function reachGraphQL (path, query, queryParams = )
try
return await transport(path, query, queryParams);
catch (error)
console.log(error)
【讨论】:
它们会导致以下情况:bundle.js:53 Promise _d: Object bundle.js:125 ReferenceError: error is not defined(...) but does not respond with the retrieved information.跨度> 如 cmets 所述,.catch(error);
是个问题。以上是关于返回未定义的异步函数的主要内容,如果未能解决你的问题,请参考以下文章