javascript - Javascript fetch 中 URL 中异步函数的值

标签 javascript reactjs react-native

下面的代码在一个 React Native 应用程序中:

假设我在 API.js 文件中有以下函数:

export function getUsers() {
    return fetch(BASE_URL+'/users')
    .then(response => {
        return response;
    })
}

我的应用程序的 BASE URL 是动态的,或者可以由用户自定义。这意味着,我将此值保留在我的应用程序的 AsyncStorage 中。

这意味着,AsyncStorage.getItem('BASE_URL') 保存我的实际 BASE_URL 的值。问题是,getItem 函数本身是一个 promise 函数。那只是将它包装成一个 promise 语法才能使它工作。例如,

AsyncStorage.getItem('BASE_URL').then(url => {
    console.log(url) //gets the URL here properly
});

我的问题是,如何用这个值实际替换获取请求中的 BASE_URL 变量?

请记住,API.js 文件不是“组件”。它仅包含不同 API 端点的导出函数。

最佳答案

您可以使用 promise chaining ,其中 AsyncStore#getItem 的结果将用作 fetch 调用的输入。链接文档很好地解释了您所面临的情况

A common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. We accomplish this by creating a promise chain.

因此,您需要对给定代码进行的更改是

export function getUsers() {
  return AsyncStorage.getItem('BASE_URL').then(url => {
    return fetch(url+'/users').then(response => response.json());
  }); 
}

您可以使用 getUsers() 而不必担心 BASE_URL。这也确保了关注点分离。

希望这会有所帮助!

关于javascript - Javascript fetch 中 URL 中异步函数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53183816/

相关文章:

javascript - 通过属性查找一个数组中不存在于另一个数组中的对象

javascript - 如何定位 iFrame 内的文本字段?

react-native - react native : Exception thrown while executing UI block: put reactNavSuperviewLink back

ios - Expo ImagePicker 在 IOS Gallery 未打开时崩溃

javascript - 如何防止计时器在浏览器刷新时重置?

javascript - CSS 和 HTML : How to create an Expanding DIV On Click?

javascript - 为什么在导出组件而不是导入组件时应用 HOC

javascript - 防止组件在经过身份验证后显示

javascript - 如果刷新页面则找不到 React Router URL - 创建 React App

android - React Native DrawerLayoutAndroid 引用不起作用