實(shí)現(xiàn)如下函數(shù) function sleep(timeout: number): Promise { throw new Error('Not implemented'); }
async function sleep(timeout){
return new Promise(resolve=>setTImeout(timeout, resolve))
}
new Promise((resolve,reject)=>{
await sleep(1000)
try{
throw new Error(xxxx)
}catch(e){
reject(e)
}
})
.then()
.catch()
修改上述函數(shù)的接口和實(shí)現(xiàn),讓該函數(shù)支持取消。也就是說茶宵,可以在sleep沒有結(jié)束前拗馒,promise提前resolve
function updateUser() {
let resolve, reject, cancelled;
const promise = new Promise((resolveFromPromise, rejectFromPromise) => {
resolve = resolveFromPromise;
reject = rejectFromPromise;
});
fetchData()
.then(wrapWithCancel(updateUserData))
.then(wrapWithCancel(updateUserAddress))
.then(resolve)
.then(reject);
return {
promise,
cancel: () => {
cancelled = true;
reject({ reason: 'cancelled' });
}
};
function wrapWithCancel(fn) {
return (data) => {
if (!cancelled) {
return fn(data);
}
};
}
}
const { promise, cancel } = updateUser();
// 等一會(huì)...
cancel(); // 用戶還是會(huì)被更新