JavaScript承诺范围问题



我认为在以下问题上有问题,我的印象是,这应该返回带有100 a的字符串,其次是100 b,但是当调用时:

  const otherm = require("./testpromise.js")
console.log("calling promise now")
otherm.daycent_promise("me","lol").then(function(res,err){
  console.log(res);
  if(err!=null){
    console.log("there was an error"+err)
  }
}) 

来自另一个文件:

module.exports={
  daycent_promise: function (username,password){
    return somefunction(username,password)
  }
}

var somefunction = function(username, password){
  return new Promise(function(resolve,reject){
    if(username=="me"){
      var str = "";
      for(i=0;i<100; i++){
        str=str.concat("a")
      }
      for(x=0;x<100;x++){
        //console.log("testing")
        addgo(str)
        //str=str.concat("b");
      }
    }
resolve(str);
  })
}

function addgo(str){
  //console.log("testing")
str=str.concat("b");
  return str
}

,即使Addgo((正在运行,我所获得的只是100 A的输出。这里发生了什么?

字符串按值传递。而且您无法突变字符串,每个修改都会创建一个新的字符串。因此,当您这样做时:

addgo(str);//passes ""
console.log(str);//still "" never changed
function addgo(str){//own variable containing ""
 //console.log("testing")
 str=str.concat("b");//internal str is now "b"
  return str;//never used
}

解决方案:

str=addgo(str);//str is overriden with "b"

顺便说一下,要容易得多:

async function somefunction(username,password){
 return username==="me"?"a".repeat(100)+" b".repeat(100):undefined;
}

替换str与来自addgo的结果

 for(x=0;x<100;x++){
    //console.log("testing")
   str=addgo(str)
    //str=str.concat("b");
  }

最新更新