实现如下函数 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()
修改上述函数的接口和实现,让该函数支持取消。也就是说,可以在sleep没有结束前,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();
// 等一会...
cancel(); // 用户还是会被更新