Promise中reject能否传多参数?为何catch无法接收多参数
Promise的reject多参数传递问题
我在使用Promise时,尝试通过reject({k1:v1},{k2:v2})传入多个对象,再用catch(prop1,prop2)获取数据,但无法正常工作。运行代码时,第二个参数始终获取不到,报错Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'str')。虽然用解构语法能解决,但想知道为什么必须用解构,以及第一个对象能正常获取、第二个却报错的原因。
代码示例
const request = (url) => { return new Promise((resolve, reject) => { setTimeout(() => { const random = Math.random(); if (random < 0.6) { resolve(); } else { reject({ status: 404 }, { str: "nice way to go" }); } }, 3000); }); }; request("/users") .then(() => { console.log("ok welcome"); }) .catch((found, strn) => { console.log(found.status); console.log("the page is not found"); console.log(strn.str);//运行此行时出现Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'str') });
问题解析
核心原因:Promise的reject/catch只处理单个参数
- reject方法的限制:根据Promise规范,
reject()只能接收一个参数作为拒绝原因。你传入的第二个对象{ str: "nice way to go" }会被直接丢弃,根本不会被传递到后续的catch回调中。 - catch回调的限制:对应的,
catch()的回调函数只会接收到reject传递来的那唯一一个参数。所以你写的catch(found, strn)里,strn永远是undefined,自然会触发读取undefined属性的报错。
解构能生效的本质
你用解构能正常工作,并不是因为解构支持多参数接收,而是你可能提前把多个数据打包成了单个对象/数组传入reject,解构只是从这一个参数里提取对应的属性或元素,本质还是在处理单个参数。
正确实现方式
如果需要传递多个数据,必须把它们打包成一个整体(对象或数组)传入reject,再在catch里处理这个整体:
方式1:打包为单个对象
const request = (url) => { return new Promise((resolve, reject) => { setTimeout(() => { const random = Math.random(); if (random < 0.6) { resolve(); } else { // 将多个数据合并到一个对象中 reject({ status: 404, str: "nice way to go" }); } }, 3000); }); }; request("/users") .then(() => { console.log("ok welcome"); }) .catch((error) => { console.log(error.status); console.log("the page is not found"); console.log(error.str); // 正常读取 });
方式2:打包为数组
const request = (url) => { return new Promise((resolve, reject) => { setTimeout(() => { const random = Math.random(); if (random < 0.6) { resolve(); } else { // 将多个数据放入数组中 reject([{ status: 404 }, { str: "nice way to go" }]); } }, 3000); }); }; request("/users") .then(() => { console.log("ok welcome"); }) .catch(([found, strn]) => { console.log(found.status); console.log("the page is not found"); console.log(strn.str); // 正常读取 });
内容的提问来源于stack exchange,提问作者Anime Club
相关产品推荐
相关产品推荐

