gpt4 book ai didi

javascript - 从另一个文件调用异步函数

转载 作者:行者123 更新时间:2023-12-01 00:11:31 24 4
gpt4 key购买 nike

我有一个类,我从它调用 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 中导入它。

For more on ES6 import/export .

示例:

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

关于javascript - 从另一个文件调用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60042807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com