我对 JavaScript 中的所有异步内容还是陌生的,并且在处理一些 Promise 时遇到了一些令人困惑的情况。这是我当前的代码:
exists(filename, targetDir){
const filepath = path.join(targetDir || this.getTargetDir(), filename);
// plug in any one method from below
}
当我查看其他人的代码时,我看到他们解析这样的值(插入上面的代码):
// method 1
return request(this.getUrl(filepath))
.then(res => {
return Promise.resolve(res.statusCode === 200);
})
.catch(() => {
return Promise.resolve(false);
});
// method 2
return request(this.getUrl(filepath))
.then(res => {
Promise.resolve(res.statusCode === 200);
})
.catch(() => {
Promise.resolve(false);
});
// method 3
return request(this.getUrl(filepath))
.then(res => {
return res.statusCode === 200;
})
.catch(() => {
return false;
});
// method 4
return new Promise((resolve, reject) => {
request(this.getUrl(filepath))
.then(res => {
resolve(res.statusCode === 200);
}
.catch(() => {
resolve(false);
};
});
在这种情况下哪些是正确的?哪些是不正确的?这取决于场景吗?推荐其中哪一款?如有好的解释将不胜感激,谢谢!
说明: exists
是一个类方法,它返回一个解析为 bool 值的 Promise,其中 true
表示 URL 存在,并且false
表示它不存在。
澄清#2:如果发生错误,exists
应解析为 false
。
最佳答案
方法 1 是正确的,但不必要地复杂。
方法 2 是完全错误的。
您创建了新的 Promise,但它们不会填充到任何地方,因此它们会在函数结束时被释放。
它相当于:return request(this.getUrl(filepath)).catch(err => undefined);
方法 3 是最好的方法。
方法 4 也会解析为 corect 值,但它是一种反模式。
What is the explicit promise construction antipattern and how do I avoid it?
关于javascript - 哪种从 Promise 解析值的方法是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45663100/