说我在应用程序中有很多承诺,就像这样:
const fetchUser = id => new Promise((resolve, reject) => {
const request = new XMLHttpRequest()
request.open('GET', 'blabla')
request.onload = () => {
if (request.status >= 400 && request.status <= 500) {
reject(Error(JSON.parse(request.responseText)))
} else {
resolve(JSON.parse(request.responseText))
}
}
request.onerror = () => reject(Error('There was a problem when fetching a user'))
request.send()
})
这是不好的做法,因为我只是复制并粘贴我做出的每个Promise的request.onload
和request.onerror
部分。所以我可以做这样的事情:
request.onload = handleLoadedRequest
request.onerror = handleBadRequest
并创建这两个新功能。但是,如何在这些函数中resolve
和reject
?
const handleBadRequest = () => reject(Error('Oops!'))
答案 0 :(得分:2)
您可以使用Promise.resolve()
和Promise.reject()
来立即解决和拒绝Promise。当拒绝Promise将其包装在Error对象中(如果尚未包装)时,这也是一个好习惯。这样,您将拥有堆栈跟踪。有关示例,请参见Mozilla文档:https://developer.mozilla.org/en-US/docs/web/javascript/reference/global_objects/promise/reject
我通常将ajax请求和XHR请求包装在一个返回Promise的函数中;这称为Promisify。请参阅此帖子,以获取有关规范XHR的示例:https://stackoverflow.com/a/30008115/1617161
您实际上并不需要将resolve和reject函数传递给其他函数。您的其他职能将是解决或拒绝自己的Promise的Promises;允许链接Promise。然后,在调用链中的Promises上调用.then()和.catch()以继续或捕获错误。
答案 1 :(得分:1)
将解析和拒绝简单地传递给handleLoadedRequest和handleBadRequest函数。
const handleLoadedRequest = (resolve, reject) => () => {
...
}
const handleBadRequest = (resolve, reject) => () => {
...
}
const fetchUser = id => new Promise((resolve, reject) => {
const request = new XMLHttpRequest()
request.open('GET', 'blabla')
request.onload = handleLoadedRequest(resolve, reject);
request.onerror = handleBadRequest(resolve, reject);
request.send()
})