我很难弄清楚 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)
})
}
首先,我预计函数 err
中的错误处理中的 handleClick
将是消息说 'Failed to fetch data'
因为函数 Promise.reject()
中的 getData()
返回 { {1}}。
然而,它似乎返回了对象reject.message
。
这就是为什么它需要在函数 { success: false, message: 'Failed to fetch data.' }
中设置 err.message
才能获取消息字符串。
这是否证明即使您将返回值设置为 handleClick
,Promise.reject()
也始终返回对象?
如果是这样,result.message
的行为会有所不同。
它返回Promise.resolve()
,因此与错误处理不同,它不需要在函数result.propertyData
中设置为data.propertyData[key]
。
它们,handleClick
和 Promise.resolve()
返回的值是否不同?还是我遗漏了什么?
我希望这能很好地解释我的困惑。 谢谢。
答案 0 :(得分:0)
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);
});
}