题目描述:
/** * const remoteAdd = async (a, b) => new Promise(resolve => { setTimeout(() => resolve(a + b), 1000); }); // 请实现本地的localAdd方法,调用remoteAdd,能最优的实现输入数字的加法 async function localAdd(...inputs) { // 你的实现 inputs.reduce((pre, cur) => { this.remoteAdd(pre, cur).then(res => { return res }) }) } // 请用示例验证运行结果: localAdd(1, 2) .then(result => { console.log(result); // 3 }); localAdd(3, 5, 2) .then(result => { console.log(result); // 10 }); * */
题目答案:
localAdd(3, 5, 2).then(res => {
console.log('sum=' + res)
})
function remoteAdd(a, b) {
return new Promise(resolve => {
setTimeout(() => resolve(a + b), 1000)
})
}
function localAdd (...inputs) {
let sum = inputs.reduce(async (pre, cur) => {
let preV = 0
let val = 0
if (typeof pre === 'object') {
await pre.then(res => {
preV = res
})
} else {
preV = pre
}
await remoteAdd(preV, cur).then(res => {
val = res
})
return val
})
return new Promise(resolve => {
resolve(sum)
})
}