我正在使用一个辅助函数 ( fetchGet) 返回一个返回承诺 ( 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');
}
Run Code Online (Sandbox Code Playgroud)
我是否需要fetchGet像上面那样将函数声明为异步函数,以便它返回承诺?
或者我可以将其声明为正常的同步函数,如下所示?(对于该函数来说,这确实是相同的情况getSpecificData)
function fetchGet(url) {
return fetchWrapper(url, 'GET');
}
Run Code Online (Sandbox Code Playgroud)