gpt4 book ai didi

javascript - 嵌套 promise : make two promise calls back to back, 传递值

转载 作者:行者123 更新时间:2023-11-30 19:08:25 26 4
gpt4 key购买 nike

我目前正在为我的电子应用程序构建一个许可系统。但我在以下方面没有取得成功:

  1. promise 提示用户输入(电子提示模块)
  2. 之后立即对服务器进行 ajax 调用
  3. 评估响应(来自服务器端脚本的 1\n 或 0\n)

令人头疼的是在从提示符(其结构为 promise )获取用户输入后运行 ajax 调用并实际等待它完成。

到目前为止,我一直在尝试重组我的 promise ,例如:

(1)

prompt().
then(ajax()).
then(evaluate()).
catch()

(2)

prompt().
then(ajax().
then(evaluate())).
catch()

这就是我目前所在的位置,ajax 函数不返回任何要传递的内容。

首先是提示,它相应地工作,返回它的值。

function activeValidation(){
try{
prompt({
title: "Enter key",
label: "Enter your key",
value: "",
alwaysOnTop: true,
autoHideMenuBar: true,
inputAttrs: {
type: 'text'
},
type: "input"
})

令人头疼的是这个部分,ajax 部分。

        .then(function(userinput){
return new Promise(function(resolve,userinput){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
resolve(req.responseText);
}
}
req.open("GET","someCGIscript?key="+userinput,true);
req.send();
}).then(function(response){
if(response == "1\n"){
runProgram();
}
else{
}
}).catch(function(e){
console.error(e);
terminate();
})});
}
catch(e){
console.log(e.name);
console.log(e.message);
terminate();
}
}

我已经尝试从 resolve(req.responseText); 中打印 ajax Promise 的值,但在以下段中返回未定义。

之后我尝试重组这两个 promise (嵌套和第一个 promise 的 .then),但没有成功。

我相信这是正确构建 promise 的问题,但我仍然是 Promises 的新手,至少在 js 方面:)。

最佳答案

您的 new Promise 回调函数中存在参数不匹配。第二个参数与 userinput 无关,而是提供给您的拒绝回调(以备不时之需)。通过调用它 userinput,您无法访问 userinput 的实际值,因为它是在其上方传递的。

因此,HTTP 请求将是类似 someCGIscript?key=function () { [native code] } 的内容,这显然会导致不希望的 HTTP 响应。

所以在 new Promise 回调函数参数列表中,将其称为 reject 或完全省略它。

关于javascript - 嵌套 promise : make two promise calls back to back, 传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58748797/

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