簡體   English   中英

反應原生無法從 function 獲取數據

[英]react native cant get data from function

我想獲取產品庫存並詳細使用它,但我有問題

我有這樣的功能。

async function getStock(productId, erp_code) {
    let itemsStock;
    await fetch(`${GET_STOCK}${productId}`, requestOptions)
      .then(response => response.json())
      .then(result => itemsStock = result[erp_code][0].LotQTY)
      .catch(error => console.log('error', error));
    console.log(itemsStock);   i cant console.log the data 
    return itemsStock;
  }

但作為回報,我得到了 promise 但這不是我想要的。

我的意思是我在 function 中獲得了我需要的數據,但我無法從 function 中使用它

這有點煩人

Promise {_U: 0, _V: 0, _W: null, _X: null}

我怎樣才能解決這個問題?

假設您以預期的格式獲得響應,您需要返回值而不是分配它。

async function getStock(productId, erp_code) {
    const itemsStock = await fetch(`${GET_STOCK}${productId}`, requestOptions)
      .then(response => response.json())
      .then(result => result[erp_code][0].LotQTY)
      .catch(error => console.log('error', error));
    console.log(itemsStock);
    return itemsStock;
  }

此外,您可以只使用 async-await 方法而不是.then.catch鏈:

async function getStock(productId, erp_code) {
    try {
        const response = await fetch(`${GET_STOCK}${productId}`, requestOptions);
        const result = await response.json();
        const itemsStock = result[erp_code][0].LotQTY;
        console.log(itemsStock);
        return itemsStock;
    } catch (error) {
        console.log({ error });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM