Promise.rejectt()返回的值与Promise.resolve()不同



我很难弄清楚Promise.reject()是如何返回其值的。

const propertyData = {
id: 1,
propertyName: '1BR Japanese-style Private Room near Kyoto Station'
}
function handleClick(e) {
getData()
.then(data => {
console.log(data.id, data.propertyName); // -> 1, '1BR Japanese-style Private Room near Kyoto Station'
})
.catch(err => {
console.log(err.message); // -> 'Failed to fetch data.' if it's only 'err', it returns the object.
})
}
function getData() {
return fetchData()
.then(result => {
if(result.success){
return Promise.resolve(result.propertyData);
} else {
return Promise.reject(result.message);
}
})
}
function fetchData() {
return new Promise((resolve, reject) => {
let rand = Math.floor(Math.random()*11)
setTimeout(() => {
if(rand >= 3 && rand <= 10){
resolve({ success: true, propertyData: propertyData });
} else {
reject({ success: false, message: 'Failed to fetch data.' });
}
}, 1000)
})
}

首先,我预计函数handleClick中的错误处理中的err将是说'Failed to fetch data'的消息,因为函数getData()中的Promise.reject()返回reject.message

然而,它似乎返回了对象{ success: false, message: 'Failed to fetch data.' }。这就是为什么它需要在函数handleClick中设置err.message才能获得消息字符串。这是否证明Promise.reject()总是返回对象,即使您设置了类似result.message的返回值?

如果是这样的话,Promise.resolve()看起来会有不同的表现。它返回result.propertyData,因此与错误处理不同,它不需要在函数handleClick中设置为data.propertyData[key]

Promise.resolve()Promise.reject()的返回值是否不同?还是我错过了什么?

我希望这能很好地解释我的困惑。非常感谢。

const propertyData = {
id: 1,
propertyName: "1BR Japanese-style Private Room near Kyoto Station",
};
function handleClick(e) {
fetchData()
.then((data) => {
// We are resolving Object with properties
// 1. success
// 2. propertyData (declared on line 1)
// e.g. Accessing those
//  - data.success OR - data.propertyData
const { id, propertyName } = data.propertyData; // Simple destruction of data.propertyData;
console.log(id, propertyName);
})
.catch((err) => {
console.log(err.message); // -> 'Failed to fetch data.' if it's only 'err', it returns the object.
});
}
function fetchData() {
return new Promise((resolve, reject) => {
let rand = Math.floor(Math.random() * 11);
setTimeout(() => {
if (rand >= 3 && rand <= 10) {
//{ This is what will be the resolved data in .then(data => ) }
// It can be anything you want string, Object, boolean w/e
resolve({ success: true, propertyData });
} else {
//{ This is what will be the resolved value in .catch()
// Does not necessarily have to be Object
// But if you pass only string then in your .catch(err => )  : err here will be string
// In your case err will be Object with props 'success' and 'message'
// To access them u go err.message OR err.success
reject({ success: false, message: "Failed to fetch data." });
}
}, 1000);
});
}

最新更新