[英]How do I do two operations per one ternary option in node.js?
There is a condition, which is also a ternary option 有条件,这也是三元选择
?spotify.search({type:'track',query:`${d}`},(e2,d2)=>!!e2
So if there is an error or if there is no error it goes to 因此,如果有错误或没有错误,它将转到
?console.log(e2)
:console.log(`Artist ${d2.tracks.items[0].artists[0].name}, album ${d2.tracks.items[0].album.name}, song ${d2.tracks.items[0].name}, preview url ${d2.tracks.items[0].preview_url}`))
However I want to do more than console.log for the second option.. I also want to append a log text file without losing data from the callback function. 但是,对于第二个选项,我想做的比console.log还要多。我还想附加一个日志文本文件,而不会丢失回调函数中的数据。 Is there any way to do both console.log and the line below for one ternary option?
有什么办法可以同时执行console.log和下面的三进制选项的代码行吗?
require(`fs`).appendFile(`log.txt`,`Artist ${d2.tracks.items[0].artists[0].name}, album ${d2.tracks.items[0].album.name}, song ${d2.tracks.items[0].name}, preview url ${d2.tracks.items[0].preview_url}`,`utf8`,e=>e?console.log(e):true)
Here it is recognizing it as undefined 在这里,它识别为未定义
(e2,d2)=>!!e2
?console.log(e2)
:(console.log(`Artist ${d2.tracks.items[0].artists[0].name}, album ${d2.tracks.items[0].album.name}, song ${d2.tracks.items[0].name}, preview url ${d2.tracks.items[0].preview_url}`)),
require(`fs`).appendFile(`log.txt`,`Artist ${d2.tracks.items[0].artists[0].name}, album ${d2.tracks.items[0].album.name}, song ${d2.tracks.items[0].name}, preview url ${d2.tracks.items[0].preview_url}`,`utf8`,e3=>e3?console.log(e3):true))
You can use the comma operator, which evaluates a comma-separated list of expressions and returns the value of the last expression: 您可以使用逗号运算符,该运算符计算逗号分隔的表达式列表并返回最后一个表达式的值:
? console.log(e2)
: (
console.log(`Artist ${d2.tracks.items[0].artists[0].name}, album ${d2.tracks.items[0].album.name}, song ${d2.tracks.items[0].name}, preview url ${d2.tracks.items[0].preview_url}`)),
require(`fs`).appendFile(`log.txt`,`Artist ${d2.tracks.items[0].artists[0].name}, album ${d2.tracks.items[0].album.name}, song ${d2.tracks.items[0].name}, preview url ${d2.tracks.items[0].preview_url}`,`utf8`,e=>e?console.log(e):true)
);
But I wouldn't recommend it, it's not very readable. 但是我不建议这样做,因为它不太可读。 The conditional operator should probably only be used when you need to use the resulting expression - otherwise, use
if
/ else
. 条件运算符可能仅应在需要使用结果表达式时才使用-否则,请使用
if
/ else
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.