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

所以问题是我必须得到第一个n自然数的总和,但条件是


1.使用辅助函数返回一个 promise


2.不能+在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 is


function 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;

}


慕沐林林
浏览 161回答 3
3回答

MYYA

找到answer较小的问题n - 1,then添加n到answer使用sumP-function natSum(n){&nbsp; if (n === 0)&nbsp; &nbsp; return Promise.resolve(0)&nbsp; else&nbsp; &nbsp; return natSum(n - 1).then(answer => sumP(n, answer))}// provided helper functionfunction sumP(x,y){&nbsp; &nbsp; return new Promise((resolve,reject)=>{&nbsp; &nbsp; &nbsp; &nbsp; resolve(x+y);&nbsp; &nbsp; });}natSum(4).then(console.log) // 10natSum(5).then(console.log) // 15natSum(6).then(console.log) // 21用箭头重写,我们可以去除很多语法噪音——const sumP = (x, y) =>&nbsp; Promise .resolve (x + y)const natSum = n =>&nbsp; n === 0&nbsp; &nbsp; ? Promise .resolve (0)&nbsp; &nbsp; : natSum (n - 1) .then (r => sumP (n, r))natSum (4) .then (console.log) // 10natSum (5) .then (console.log) // 15natSum (6) .then (console.log) // 21使用async并且await只隐藏像Promise.resolve和这样的 Promise 原语.then-const sumP = async (x, y) =>&nbsp; x + y //<-- returns promise because of "async" keywordconst natSum = async n =>&nbsp; n === 0&nbsp; &nbsp; ? 0&nbsp; &nbsp; : sumP (n, (await natSum (n - 1)))natSum (4) .then (console.log) // 10natSum (5) .then (console.log) // 15natSum (6) .then (console.log) // 21

慕尼黑8549860

您可以使用 recursionfunction sumP(x, y) {&nbsp; //Helper function&nbsp; // Always resolves&nbsp; return new Promise((resolve, reject) => {&nbsp; &nbsp; resolve(x + y);&nbsp; });}const naturalSum = (n, i = 1, res = 0) => {&nbsp; sumP(res, i).then(data => {&nbsp; &nbsp; if (i == n) {&nbsp; &nbsp; &nbsp; console.log(data);&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; naturalSum(n, ++i, data)&nbsp; });};naturalSum(5)naturalSum(6)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript