You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中Promise无返回值,递归查找JSON父对象失败求助

Troubleshooting Promise Return Value Issues in React Native's findItem/searchJson Functions

Hey there, let's work through this frustrating issue where your recursive JSON search isn't returning the parent object you're looking for. This is a super common pitfall with async recursive code—let's break down the likely problems and fix them step by step.

Common Causes & Fixes

1. Your searchJson isn't handling recursion + async correctly

If searchJson is supposed to be async but isn't properly passing up the found result through recursion, it'll either resolve early with nothing or never resolve at all. Let's rewrite it to explicitly handle async recursion:

// Async recursive function that properly returns the found parent
const searchJson = async (data, targetId) => {
  for (const item of data) {
    // Check if this item is the target (adjust condition to match your data structure)
    if (item.id === targetId) {
      // Return the parent object directly when found
      return item.parent; 
    }
    // If the item has children, recursively search them
    if (item.children && item.children.length > 0) {
      const recursiveResult = await searchJson(item.children, targetId);
      // If recursion found a match, pass it up immediately
      if (recursiveResult) {
        return recursiveResult;
      }
    }
  }
  // Return null if no match was found in this branch
  return null;
};

The key here is await-ing the recursive call and returning the result as soon as it's found—this ensures the Promise resolves with the correct value instead of just finishing the loop early.

2. findItem isn't awaiting the async searchJson call

If you're calling searchJson without await or .then(), you'll just get a pending Promise instead of the actual parent object. Let's fix findItem to handle async properly:

// Make findItem async so we can await searchJson's result
const findItem = async (targetId) => {
  try {
    // Replace with your actual JSON data source (state, import, etc.)
    const jsonData = yourAppJsonData; 
    const parentItem = await searchJson(jsonData, targetId);
    
    if (parentItem) {
      console.log("Found parent object:", parentItem);
      return parentItem; // Pass the result back to the caller
    } else {
      console.log("No parent found for ID:", targetId);
      return null;
    }
  } catch (error) {
    console.error("Error during JSON search:", error);
    throw error; // Let the caller handle the error if needed
  }
};

3. Your button click handler isn't handling the async result

Since findItem returns a Promise, your back button's onPress handler needs to account for that. Use async/await directly in the handler:

// Example React Native button click handler
const handleBackPress = async () => {
  const targetId = yourTargetItemId; // Replace with your actual ID
  const parentItem = await findItem(targetId);
  
  // Do something with the parent item (e.g., navigate back with data)
  if (parentItem) {
    navigation.navigate("PreviousScreen", { parentData: parentItem });
  }
};

// In your component's JSX
<Button title="Back" onPress={handleBackPress} />

Key Takeaways

  • Always await recursive async calls to ensure results are passed up the stack.
  • Async functions return Promises—never forget to use await or .then() to access their resolved values.
  • Add try/catch blocks to catch errors during traversal or Promise resolution.

内容的提问来源于stack exchange,提问作者Rudolph Opperman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:05:40