javascript - 从另一个文件调用异步函数
问题描述
我有一个类,我从它调用 API。但我正在重构代码,我想从另一个文件中调用这个函数。这是我在 Screen 类的同一个文件中调用的当前函数。
MyScreen.js
addWishList(product) {
this.addProductsToWishlist(product);
}
async addProductsToWishlist(product){
const loggedCustomerID = await SecureStore.getItemAsync('loggedUserCustomerID');
const wishListID = await SecureStore.getItemAsync('loggedUserWishlistID');
try {
let dataRequest = {
method: 'POST',
body: JSON.stringify({
CustomerID: loggedCustomerID,
WishlistID: wishListID,
WishlistProducts: [{
ProductID: product.ProductID,
Quantity: 1,
WebSiteID: 1
}
]
}),
headers: HEADERS_API
}
const addProductsToWishlistApiCall = await fetch(ADD_PRODUCT_WISHLIST_URL, dataRequest);
const addProductsToWishlistApiResponse = await addProductsToWishlistApiCall.json();
console.log(addProductsToWishlistApiResponse.SavedWishlistProductIDs)
this.setState({wish: !this.state.wish});
} catch(err) {
console.log("Error fetching data-----------", err);
}
}
我怎么能把这个函数放在另一个文件中并从我的屏幕文件中调用它?
解决方案
您首先需要从函数定义文件中导出它,然后从 MyScreen.js 中导入它。
例子:
//------ lib.js ------
export const sqrt = Math.sqrt;
export async square = (x) => {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ main.js ------
import { square, diag } from 'lib';
(async function() {
console.log(await square(11)); // 121
})()
console.log(diag(4, 3)); // 5
推荐阅读
- oracle - 使用 MATCH_RECOGNIZE 时 FINAL SUM 的 NULLIF 翻倍
- python - 如何使用`httpretty`模拟请求
- python - 如何在 Angular 9 中集成 python 脚本?
- reactjs - 当元素出现在 50 张卡片上时,如何使用 .map() 函数在点击屏幕上显示的元素之一下方放置一个框
- c# - 如何使用正确的 MVVM 在不同的内容页面 Xamarin 中传递数据
- git - 德比安。当我使用 `git restore` 命令时,它说,这个命令不存在
- r - 如何根据字符串的第一个和第三个字符过滤一列字符串?
- java - 将 ArrayList 中的两组值与重复配对的逻辑
- python - Python:如何在 pandas.Series 中剥离字符串?
- javascript - 来自特定选择器的 JQuery 组件