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

使用await+superagent后解构list为undefined,res.body正常,求原因

Why is list undefined even though res.body is accessible?

Let's break down what's happening in your code and why you're seeing this issue:

1. Core Issue: Your destructuring targets a property that doesn't exist in res.body

First, let's clarify how your code works:

const { list } = await superagent.get(`http://${window.location.host}/api`)
  .then(res => { 
    console.log(res.body); 
    return res.body 
  })

The await keyword waits for the entire Promise chain to resolve, so it will evaluate to whatever your .then() callback returns—in this case, res.body. That means your line is equivalent to:

const { list } = res.body;

Since you confirmed res.body is accessible, the only reason list would be undefined is that res.body does not contain a property named list. This could happen for a few common reasons:

  • The API returns data under a different key (e.g., items, data, results, or even a capitalized List)
  • The list property is nested deeper in the response (e.g., res.body.data.list instead of res.body.list)
  • There's a typo in the property name (double-check spelling and case sensitivity!)

2. How to debug this

Add a few extra console logs to inspect the structure of res.body clearly:

const res = await superagent.get(`http://${window.location.host}/api`);
console.log('Full response body:', res.body);
// List all properties in res.body to check what's actually available
console.log('Keys in res.body:', Object.keys(res.body));
// Directly check the value of the supposed "list" property
console.log('res.body.list value:', res.body.list);

const { list } = res.body;
console.log(list);
return { list };

This will help you confirm exactly what properties exist in your response body.

3. Clarifying your const question

You mentioned wondering if const should wait for the assignment to complete—and you're right! The await keyword ensures that the entire const { list } = ... line doesn't execute until the Promise resolves. The issue has nothing to do with const itself; it's purely about the structure of the data you're trying to destructure.

Bonus: Simplify your code

Mixing await and .then() isn't necessary and can make logic harder to follow. The simplified code above is easier to debug and read.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:39:29