Promise链式调用遇TypeError:无法读取undefined的'main'属性
问题原因
你遇到的TypeError: Cannot read properties of undefined (reading 'main')是因为Promise链式调用中,前一个.then回调没有返回数据,导致后续.then的参数变为undefined。
看你的代码:
.then((response) => { // Displays current city city.textContent = response.name; })
这个回调函数没有return response,所以下一个.then接收的参数就是undefined,自然访问不了response.main。
解决方案
有两种常用的修复方式:
方式1:在每个需要传递数据的.then中返回response
修改后代码如下:
fetch( `https://api.openweathermap.org/`, { mode: "cors" } ) .then((response) => { console.log(response); return response.json(); }) .then((response) => { // Displays current city city.textContent = response.name; return response; // 必须返回,才能传递给下一个then }) .then((response) => { // Displays current temperature temp.textContent = `${Math.trunc(response.main.temp)}°`; return response; // 继续返回数据 }) .then((response) => { // Displays how much humidity humidity.textContent = `Humidity: ${response.main.humidity}%`; }) .catch((err) => { console.log(err); });
方式2:把相关DOM操作逻辑合并到同一个.then中
如果不需要拆分多个.then,直接把所有DOM操作放在同一个回调里,这样更简洁,也不会出现数据传递问题:
fetch( `https://api.openweathermap.org/`, { mode: "cors" } ) .then((response) => { console.log(response); return response.json(); }) .then((response) => { // Displays current city city.textContent = response.name; // Displays current temperature temp.textContent = `${Math.trunc(response.main.temp)}°`; // Displays how much humidity humidity.textContent = `Humidity: ${response.main.humidity}%`; }) .catch((err) => { console.log(err); });
补充说明
Promise链式调用的核心是每个.then的返回值会作为下一个.then的参数:
- 如果回调返回一个值,下一个
.then就接收这个值; - 如果回调没有返回值,默认返回
undefined,后续.then的参数就是undefined; - 如果返回的是新的Promise,后续
.then会等待这个Promise完成。
内容的提问来源于stack exchange,提问作者Dagger
相关产品推荐
相关产品推荐

