首页 > 解决方案 > 从另一个文件调用异步函数

问题描述

我有一个类,我从它调用 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);
    }
  }

我怎么能把这个函数放在另一个文件中并从我的屏幕文件中调用它?

标签: javascriptreact-native

解决方案


您首先需要从函数定义文件中导出它,然后从 MyScreen.js 中导入它。

有关 ES6 导入/导出的更多信息

例子:

//------ 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

推荐阅读