Promise

作者: Hsugar | 来源:发表于2020-05-26 20:58 被阅读0次

    实现如下函数 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(); // 用户还是会被更新
    

    相关文章

      网友评论

          本文标题:Promise

          本文链接:https://www.haomeiwen.com/subject/qzcbahtx.html