首页 > 解决方案 > 如何在范围内使用异步函数的返回

问题描述

简介

所以我是 JavaScript 新手,我想知道如何使用异步函数的返回而不使用 .then 或任何类似的东西(如果没有,那么是否可以以我可以访问的方式使用它在 signupData() 函数的范围内返回)。因此,我使用 ECIES 方案加密事物,使用 Secp256k1 密钥发送到 API 以供以后使用,但是,我认为帖子中 encryptMes 部分下的 .encrypt 调用了一个承诺。下面是相关代码:

注册.html

       <form id="login-form" name ="signup-form">
            <input class="login-form-field" type="text" name="user" placeholder="username">
            <input class="login-form-field" type="text" name="email" placeholder="email">
            <input class="login-form-field" type="password" name="dob" placeholder="date of birth">
            <br>
            <!--<button class="actionButton"></button>-->
            <INPUT TYPE="button" class="button-success" NAME="button" Value="sign up" onClick="signupData(this.form)">
              <br>
              <div class="signup">
              <a href="login.html">login</a>
              </div>
        </form>
  function signupData(form) //add to this script
    {
      console.log("signup data is starting");
      var user = form.user.value;
      var email = form.email.value;
      var dob = form.dob.value;

      console.log("checkpoint: 1");

      genSKey();

      console.log("checkpoint: 2");

      console.log("checkpoint: 3");

      var enUser = encryptMes(user); //why does this invoke a promise?
    
      var enDOB = encryptMes(dob);

      var data = {name:"LifeNet", members:{}} //you added members to the same area in the object so it is always replacing members since it's the field of data

      data.members[enUser] = {profilePic:{},enDOB, listeners:{}, listening:{}, friends:{}, requested:{}, blocked:{}, channel:false}

      console.log("checkpoint: 3");

      console.log({data});

      apiPost({data});
      //pass the signup function in here

      //hash the variables and send to celox network
      //console.log(JSON.stringify({data}));
      //alert (`copy and save your Private Key to somewhere safe: ${skey}`);
      //window.location.href= "login.html";
    }

加密功能:

window.encryptMes = async function(data)
{
    //for this you need to get the sender's public key to encrypt the message
    console.log("encryptmes: began");
    var pkey = genPKey();

    if (pkey === null || undefined) 
    {
      
      console.log('You do not have a key pair');

    }

    var encryptedMes = await eccrypto.encrypt(pkey, Buffer.from(data));

    var enMes = encryptedMes.toString('hex');

    console.log(encryptedMes); //could be this since it is not stringified when it goes into celox network
    console.log(enMes);

    return enMes;
}

焦点:我如何访问异步函数的返回,encryptMes,没有“.then”,所以我可以在html文件中的signupData()函数的范围内使用它?

标签: javascripthtmlnode.jsasynchronouspromise

解决方案


如果您的 signupData 函数也是异步的,那么您可以使用 await 关键字variable = await asyncfunct(params)


推荐阅读