Nic*_*asL 4 javascript synchronous promise async-await
我正在使用一个辅助函数 ( 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)
函数是否需要声明为异步才能返回 Promise?
一点都不。事实上,promise 早在async函数之前就已经存在了。
你的包装可以是:
function fetchGet(url) {
return fetchWrapper(url, 'GET');
}
Run Code Online (Sandbox Code Playgroud)
如果您不在函数内部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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1196 次 |
| 最近记录: |