一、题目:如下为一段代码,请完善sum函数,使得 sum(1,2,3,4,5,6) 函数返回值为 21 ,需要在 sum 函数中调用 asyncAdd 函数,且不能修改asyncAdd函数
function asyncAdd(a,b,callback) {
setTimeout(function(){
callback(null, a+b)
},1000)
}
async function sum(...rest) {
}
let start = window.performance.now()
sum(1, 2, 3, 4, 5, 6).then(res => {
console.log(res)
console.log(`程序执行共耗时: ${window.performance.now() - start}`)
})
二、解决
function asyncAdd(a, b, callback) {
setTimeout(function () {
callback(null, a + b);
}, 1000);
}
async function sum1(...rest) {
let result = rest.shift();
for (let i = 0; i < rest.length; i++) {
const num = rest[i];
result = await new Promise((resolve) => {
asyncAdd(result, num, (_, pre) => resolve(pre));
});
}
return result;
}
async function sum2(...rest) {
if (rest?.length <= 1) {
return rest[0] ?? 0;
}
const promises = [];
for (let i = 0; i < rest.length; i += 2) {
promises.push(
new Promise((resolve) => {
if (rest[i + 1] === undefined) {
resolve(rest[i]);
} else {
asyncAdd(rest[i], rest[i + 1], (_, pre) => resolve(pre));
}
})
);
}
const result = await Promise.all(promises);
return await sum2(...result);
}
async function sum3(...rest) {
let result = 0;
const obj = {};
obj.toString = () => result;
const promises = [];
for (let num of rest) {
promises.push(
new Promise((resolve) => {
asyncAdd(obj, num, (_, pre) => resolve(pre));
}).then((res) => (result = res))
);
}
await Promise.all(promises);
return result;
}
let start = window.performance.now();
sum3(1, 2, 3, 4, 5, 6).then((res) => {
console.log(res);
console.log(`程序执行共耗时: ${window.performance.now() - start}`);
});