可以给promise中的reject()赋多个参数并回调它们的值



在使用承诺时,我试图将多个对象分配给拒绝({k1:v1},{k2:v2}),然后使用catch(prop1,prop2)检索数据,但它不工作。

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);//when I run this code line I get ( Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'str'))
});

我尝试使用结构化,它确实工作,但我想知道为什么它应该只在我使用结构化时工作,因为它在第一个对象上工作得很好,并且在试图访问第二个对象

的属性时给了我一个错误。

Promise.reject()只接受一个reason参数。如果你想传递多个值,把它们包装在一个数组(或对象)中:

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);
});

最新更新