Javascript 函数是否应该避免通过三元条件拒绝承诺?
Should a Javascript function avoid reject a promise via a ternary condition?
我看到了一段我觉得很有趣的代码。感觉这里有很多问题。我在这里看到一个三元组返回错误而不是值吗?因此,这不应该是 if
-else
吗?
const aData = await response.json();
return await new Promise((resolve, reject) => {
(aData.title === aName)
? resolve('A data was found')
: reject(new Error('Incorrect data was returned'));
});
resolve
和 reject
都只是 return 值 undefined
,而您的回调函数根本没有 return
任何东西。使用三元运算符使其成为单个表达式是没有用的。
为了清楚起见,你最好写
if (aData.title === aName) resolve('A data was found');
else reject(new Error('Incorrect data was returned'));
尽管您根本不应该在这里使用 new Promise
构造函数。刚刚
const aData = await response.json();
if (aData.title !== aName) throw new Error('Incorrect data was returned');
else return 'A data was found';
我看到了一段我觉得很有趣的代码。感觉这里有很多问题。我在这里看到一个三元组返回错误而不是值吗?因此,这不应该是 if
-else
吗?
const aData = await response.json();
return await new Promise((resolve, reject) => {
(aData.title === aName)
? resolve('A data was found')
: reject(new Error('Incorrect data was returned'));
});
resolve
和 reject
都只是 return 值 undefined
,而您的回调函数根本没有 return
任何东西。使用三元运算符使其成为单个表达式是没有用的。
为了清楚起见,你最好写
if (aData.title === aName) resolve('A data was found');
else reject(new Error('Incorrect data was returned'));
尽管您根本不应该在这里使用 new Promise
构造函数。刚刚
const aData = await response.json();
if (aData.title !== aName) throw new Error('Incorrect data was returned');
else return 'A data was found';