为了账号安全,请及时绑定邮箱和手机立即绑定

使用承诺的前 n 个自然数的总和?

使用承诺的前 n 个自然数的总和?

慕沐林林 2021-10-21 14:10:41
所以问题是我必须得到第一个n自然数的总和,但条件是1.使用辅助函数返回一个 promise2.不能+在main函数内部使用operator(只允许在helper函数中)。3.不能使用async-await在如此远的解决方案我来就是nat_sum =  (n) =>{let i=1,res=0;while(i<=n){    sumP(res,i++).then( data => {        res = data;        console.log(res);    });     console.log("res is ",i, res);} };//Helper function isfunction sumP(x,y){    // Always resolves     return new Promise((resolve,reject)=>{        resolve(x+y);    });}但问题是,循环只是sumP用初始值resie初始化所有对 的调用0,这意味着它只是不等待前一个承诺resolve并更新res变量。使用回调解决的相同问题如下(您可以忽略这一点,只是对问题的洞察!):function sumc(x,y,callme){    return callme(x,y);}nat_sumC = (n)=>{  let i=1,res=0;  while(i<=n){        res = sumc(res,i++,sum);    }  return res;}
查看完整描述

3 回答

?
MYYA

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


查看完整回答
反对 回复 2021-10-21
?
慕尼黑8549860

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)


查看完整回答
反对 回复 2021-10-21
  • 3 回答
  • 0 关注
  • 160 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信