async/await的特殊用法
原创
©著作权归作者所有:来自51CTO博客作者wu_qiang的原创作品,请联系作者获取转载授权,否则将追究法律责任
任何具有“.then”方法的对象都可以与async/await一起使用。
看下面代码的例子,写了个睡眠函数
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);
})();
下面还写了个轮询的例子:
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);
}
})();