3 回答
TA贡献1868条经验 获得超4个赞
找到answer较小的问题n - 1,then添加n到answer使用sumP-
function natSum(n){
if (n === 0)
return Promise.resolve(0)
else
return natSum(n - 1).then(answer => sumP(n, answer))
}
// provided helper function
function sumP(x,y){
return new Promise((resolve,reject)=>{
resolve(x+y);
});
}
natSum(4).then(console.log) // 10
natSum(5).then(console.log) // 15
natSum(6).then(console.log) // 21
用箭头重写,我们可以去除很多语法噪音——
const sumP = (x, y) =>
Promise .resolve (x + y)
const natSum = n =>
n === 0
? Promise .resolve (0)
: natSum (n - 1) .then (r => sumP (n, r))
natSum (4) .then (console.log) // 10
natSum (5) .then (console.log) // 15
natSum (6) .then (console.log) // 21
使用async并且await只隐藏像Promise.resolve和这样的 Promise 原语.then-
const sumP = async (x, y) =>
x + y //<-- returns promise because of "async" keyword
const natSum = async n =>
n === 0
? 0
: sumP (n, (await natSum (n - 1)))
natSum (4) .then (console.log) // 10
natSum (5) .then (console.log) // 15
natSum (6) .then (console.log) // 21
TA贡献1818条经验 获得超11个赞
您可以使用 recursion
function sumP(x, y) { //Helper function
// Always resolves
return new Promise((resolve, reject) => {
resolve(x + y);
});
}
const naturalSum = (n, i = 1, res = 0) => {
sumP(res, i).then(data => {
if (i == n) {
console.log(data);
return;
}
naturalSum(n, ++i, data)
});
};
naturalSum(5)
naturalSum(6)
添加回答
举报