1. 【MOKA】实现add方法,可以相加多个数据并返回结果
const addRemote = async (a, b) =>
new Promise((resolve) => {
setTimeout(() => resolve(a + b), 1000);
});
async function add(...inputs) {
}
add(1, 2).then((result) => {
console.log(result);
});
add(3, 5, 2).then((result) => {
console.log(result);
});
async function add(...inputs) {
let res = 0
for(let i = 0; i < inputs.length; i ++) {
res = await addRemote(res, inputs[i])
}
return Promise.resolve(res)
}
2. 【高途】异步执行任务
new Promise(resolve => {
console.info(1)
setTimeout(resolve, 100, 2)
console.log(3)
}).then((data) => {
console.info(data)
})
2. 【美团、知乎】高阶版异步执行任务
console.info('start')
async function async1() {
await async2()
console.log('async1')
}
async function async2() {
console.log('async2')
}
setTimeout(function() {
console.log(1)
}, 0)
new Promise(function(resolve) {
console.log(2)
for( var i=0 ; i<10000 ; i++ ) {
i == 9999 && resolve()
}
console.log(3)
}).then(function() {
console.log(4)
}).then(function () {
console.log(5)
})
Promise.resolve().then(function () {
console.log(6)
})
async1()
console.info('end')
3. 【字节】接口加载异常时,实现间隔一定的时间,重复执行n次
async reloadFn(n, interval) {
if(n === 0) return false
n--
try {
let res = await Promise.reject('err')
throw res
} catch(error) {
setTimeout(() => {
reloadFn(n, interval)
}, interval)
}
}
reloadFn(4, 1000)