gpt4 book ai didi

JavaScript Promise 返回 Pending 但我只需要值

转载 作者:行者123 更新时间:2023-12-02 21:45:48 26 4
gpt4 key购买 nike

你能帮我解决这个代码片段吗?在这一部分中,我向我的 c# Controller 发出 ajax 请求,只是为了验证电子邮件并获取 bool 值,但在此过程中, promise 返回待处理状态会产生问题,因为我实际上只需要 promise 内的值,这里是我的代码:

let Email = input;
let valida = ValidaEmail(Email);
console.log(valida);

函数

async function ValidaEmail(email) {
let promise = new Promise(resolve => {
var string = JSON.stringify(email);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/Home/EmailisValid", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = () => {
if (xhttp.readyState === 4 && xhttp.status === 200)
resolve(xhttp.response);
};
xhttp.send(string);
});
let retorno = await promise;
console.log(retorno);
}

输出: enter image description here

最佳答案

首先,您必须从 ValideEmail 返回 promise 结果。

async function ValidaEmail(email) {
let promise = new Promise(resolve => {
var string = JSON.stringify(email);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/Home/EmailisValid", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = () => {
if (xhttp.readyState === 4 && xhttp.status === 200)
resolve(xhttp.response);
};
xhttp.send(string);
});
let retorno = await promise;
console.log(retorno);
//////
return retorno;
//////
}

当您使用ValidateEmail函数时,您必须使用await或.then();

let Email = input;
///
let valida = await ValidaEmail(Email);
console.log(valida);
// or
ValidaEmail(Email).then((valida) => {
console.log(valida);
})

关于JavaScript Promise 返回 Pending 但我只需要值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60258523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com