分别使用Promise和async改写成每隔1s打印1个数字的形式
function print(n){
for(var i = 0;i <n;i++){
setTimeout(console.log, 1000, i);
}
}
print(10);
分别使用Promise和async改写成每隔1s打印1个数字的形式
function print(n){
for(var i = 0;i <n;i++){
setTimeout(console.log, 1000, i);
}
}
print(10);
const asyncSetTimeout = (timeout = 1e3, ...params) => {
let timer = 0;
let rejectRef = null;
const result = new Promise((resolve, reject) => {
rejectRef = reject;
timer = setTimeout(() => {
resolve(params);
}, timeout);
});
result.cancelTimeout = (reason) => {
clearTimeout(timer);
rejectRef(reason);
};
return result
};
const print = (times, curTime = 0) => {
asyncSetTimeout().then(() => {
console.log(curTime);
times && print(times - 1, curTime + 1);
})
}
const print = async (times, curTime = 0) => {
await asyncSetTimeout(1e3);
console.log(curTime);
times && print(times - 1, curTime + 1);
}
6 回答3.1k 阅读✓ 已解决
8 回答4.9k 阅读✓ 已解决
6 回答3.6k 阅读✓ 已解决
5 回答2.9k 阅读✓ 已解决
6 回答2.4k 阅读
5 回答6.5k 阅读✓ 已解决
4 回答2.3k 阅读✓ 已解决
async/await:
纯 Promise(有必要吗?)
也不用 Promise