Special usage of async/await

Any object with a ".then" method can be used with async/await.

Look at the following code example, wrote a sleep function

class Sleep {
    
    
  constructor(timeout) {
    
    
    this.timeout = timeout;
  }
  then(resolve, reject) {
    
    
    const startTime = Date.now();
    setTimeout(() => resolve(Date.now() - startTime), this.timeout);
  }
}

(async () => {
    
    
  const actualTime = await new Sleep(1000);
  console.log(actualTime);
})();

A polling example is also written below:

const ServerMock = {
    
    
  count: 0,
  getData() {
    
    
    if (this.count === 2) {
    
    
      return Promise.resolve([{
    
     name: "SomeName" }]);
    } else {
    
    
      this.count++;
      return Promise.reject("Error");
    }
  }
};

function fetchData(limit, time) {
    
    
  return {
    
    
    then(resolve, reject) {
    
    
      const retry = setInterval(async () => {
    
    
        limit--;
        try {
    
    
          console.log("Trying....");
          const data = await ServerMock.getData();
          if (data) {
    
    
            console.log("Resolve");
            clearInterval(retry);
            resolve(data);
          }
        } catch {
    
    
          if (limit === 0) {
    
    
            clearInterval(retry);
            reject("Limit Reached");
          }
        }
      }, time);
    }
  };
}

(async () => {
    
    
  try {
    
    
    const result = await fetchData(3, 1000);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
})();

Guess you like

Origin blog.csdn.net/wu_xianqiang/article/details/108134000