我有一个 JS 程序,它对特定 API 进行大量 fetch() 调用。我想将所有 fetch() 调用抽象为一个名为“apiService”的类,这样我的代码将更具可读性。我希望 apiService 应用一些智能,然后通过以下方式将响应返回给调用者: - apiService 应检查响应以查看是否存在错误,并且必须始终以相同的方式处理错误。 - fetch() 有时会收到一个“res”,它是原始数据,应该按原样使用,有时它会收到需要 .then(res => res.json().then(res 应用所以它可以返回一个对象。
所以我不能只从 apiService 执行“return fetch(...”,因为 apiService 需要处理一个或多个带有响应的 .then() block 。但我还需要返回一些导致调用的内容代码异步工作而不是阻塞和等待。
任何人都知道我如何构造 apiService 函数来处理 html 响应,同时也异步返回,即调用函数将在错误检查等之后接收结果对象。
最佳答案
So I can't just do a "return fetch(..." from apiService, because apiService needs to process one or more .then() blocks with the response. But I also need to return something that causes the calling code to work asynchronously and not block and wait.
这给我的感觉是你可能有点误解了 promise 。举个例子:
const doAsyncWork = () => fetch('somewhere').then(() => console.log('fetch is complete'))
// use the above function
doAsyncWork().then(() => console.log('used the fetching function'))
上述代码的输出将是
fetch is complete
used the fetching function
正如您所看到的,通过在 fetch
调用之后链接 then
,您实际上返回的是 then
的结果,而不是 fetch。另一种思考方式是,如果您调用,您实际返回的是什么
const result = a().b().c() // we are really returning the result of `c()` here.
考虑到上述内容,您绝对可以执行以下操作:
const apiCall = loc => fetch(loc).then(res => {
// do things with your response
return res
})
apiCall('someEndpoint').then(finalRes => {
console.log('this is called after fetch completed and response processed')
})
关于javascript - 如何处理 fetch() 响应并仍然异步工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52941404/