function add(num1, num2) {const num1Digits = (num1.toString().split('.')[1] || '').length;const num2Digits = (num2.toString().split('.')[1] || '').length;const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));return (num1 * baseNum + num2 * baseNum) / baseNum;
}
function asyncAdd(a, b, callback) {setTimeout(function () {callback(null, a + b);}, 1000);
}
function sumT(a, b) {return await new Promise((resolve, reject) => {asyncAdd(a, b, (err, res) => {if(!err) {resolve(res)}reject(err)})})}const test = await sumT(1, 2)
console.log(test) // 3
function sum(...args) {return new Promise((resolve) => {args.reduce((acc, cur) => acc.then((total) => sumT(total, cur)), Promise.resolve(0)).then(resolve);});
}console.time('sum');await sum(1, 2, 3, 4, 5); // 15console.timeEnd('sum');
async function sum(...args) {console.log(args); // 用于考察每次迭代的过程if (args.length === 1) return args[0]; // 如果仅有一个,直接返回let result = [];// 两两一组,如果有剩余一个,直接进入for (let i = 0; i < args.length - 1; i += 2) {result.push(sumT(args[i], args[i + 1]));}if (args.length % 2) result.push(args[args.length - 1]);return sum(...(await Promise.all(result))); // Promise.all 组内求和
} test = await sum(1, 2, 3, 4, 5);
Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.A new tool that blends your everyday work apps into one. It's the all-in-one workspace for you and your teamhttps://serious-lose.notion.site/Addition-d55df1e3417147f096855f4977ddf425
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态