javascript - 如何在范围内使用异步函数的返回
问题描述
简介:
所以我是 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()函数的范围内使用它?
解决方案
如果您的 signupData 函数也是异步的,那么您可以使用 await 关键字variable = await asyncfunct(params)
推荐阅读
- r - 在 R 中的 circlize 包中绘制图
- git - 如何在特定提交 git 后获取某些扩展的总行数
- swift - 如何在 swift 中为枚举添加更多案例
- css - 高度样式属性问题。
- xml - XSLT 1.0 - 不指定重复项和条件
- java - 如何在 stdout/stderr 准备就绪时进行回调,而不是忙于轮询?
- c++ - 我的简单 if-else 语句无法访问代码如何?
- internet-explorer - 如何使用 Selenium web-driver 中的 ie 功能处理 IE11 的 Windows 安全弹出窗口(您即将通过安全连接查看页面)?
- jquery - 计算插入符号所在的 contenteditable div 行的字符数
- vhdl - 如何在 VHDL 中将 4 位标准向量转换为 5 位向量?