我正在使用一个辅助函数(fetchGet
),该函数返回一个异步函数,该函数返回一个promise(fetchWrapper
)。是否需要将该帮助程序函数声明为异步的,以使其自身返回承诺?
我这里的情况是使用fetch,这需要在我的第一个函数中等待fetchWrapper
(为便于阅读,此处已简化):
// returns a promise
async function fetchWrapper(url, method) {
const response = await fetch(url, {method: method});
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response;
}
async function fetchGet(url) {
return fetchWrapper(url, 'GET');
}
async function getSpecificData() {
return fetchGet('/a/specific/url');
}
我是否需要fetchGet
如上所述将函数声明为异步函数,以使其返回承诺?
还是可以将其声明为如下所示的普通同步函数?(对于getSpecificData
函数,情况确实如此)
function fetchGet(url) {
return fetchWrapper(url, 'GET');
}
是否需要将函数声明为异步函数以返回承诺?
一点都不。实际上,许诺早于async
职能开始。
您的包装器可以是:
function fetchGet(url) {
return fetchWrapper(url, 'GET');
}
async
如果您不在await
函数内部使用,则不需要。您可能会选择使用它来标记该函数的异步特性,例如,作为代码内文档(IDE中的代码提示等)。但这不是必需的。
旁注:您对遇到问题fetchWrapper
。如果出现HTTP错误,它将以实现值成功undefined
。这意味着使用它的代码必须undefined
在使用它之前检查实现值以查看它是否在。我建议将HTTP错误设置为错误(拒绝):
async function fetchWrapper(url, method) {
const response = await fetch(url, {method: method});
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句