-
-
Notifications
You must be signed in to change notification settings - Fork 236
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
promise中断请求 #170
Comments
|
你这个写法不可能实现的吧,这个代码执行顺序是先执行 |
// 1.一个标准简单的promise
const promise = new Promise((resolve, reject) => {
// ... some code
if (/* 异步操作成功 */) {
resolve(value)
} else {
reject(error)
}
})
// 2.增加一个是否取消的promise判断
let cancelPromise = false
const promise = new Promise((resolve, reject) => {
// ... some code
if (/* 异步操作成功 */) {
cancelPromise ? reject({isCanceled: true}) : resolve(value)
} else {
cancelPromise ? reject({isCanceled: true}) : reject(error)
}
})
// 3.封装函数
// 3.1 第2步中内聚性不高,不符合高内聚,低耦合的代码原则。将其封装到同一个函数内
const makeCancelable = () => {
let cancelPromise = false
const wrappedPromise = new Promise((resolve, reject) => {
// ... some code
if (/* 异步操作成功 */) {
cancelPromise ? reject({isCanceled: true}) : resolve(value)
} else {
cancelPromise ? reject({isCanceled: true}) : reject(error)
}
})
return {
promise: wrappedPromise,
cancel() {
cancelPromise: true
}
}
}
// 3.2 在第3.1步中,虽然函数可以设置操作取消promise了,但是promise执行操作的代码只能写在函数内部,不通用,将其改进,promise可传参
const makeCancelable = (promise) => {
let cancelPromise = false
const wrappedPromise = new Promise((resolve, reject) => {
promise.then((value) => {
cancelPromise ? reject({isCanceled: true}) : resolve(value)
})
promise.catch((error) => {
cancelPromise ? reject({isCanceled: true}) : reject(error)
})
})
return {
promise: wrappedPromise,
cancel() {
cancelPromise: true
}
}
}
// 4.举例使用可取消的promise
const somePromise = new Promise((resolve, reject) => {
// ... some code
if (/* 异步操作成功 */) {
resolve(value)
} else {
reject(error)
}
}) // 创建一个异步操作
const cancelable = makeCancelable(somePromise) // 为异步操作添加可取消的功能
cancelable.promise
.then(() => console.log('resolved'))
.catch(({isCanceled, ...error}) => console.log('isCanceled', isCanceled))
cancelable.cancel() // 取消异步操作 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: