嵌套诺言:背对背做两个诺言,传递价值

我目前正在为我的电子应用建立许可证系统。但是我在以下方面还没有成功:

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

头痛的是在从提示符(结构化为承诺)中获取用户输入并实际上等待它完成之后运行ajax调用。

直到现在,我仍在尝试重新构建自己的诺言,例如:

(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的值,但是在以下段中返回undefined。

此后,我试图重组两个诺言(嵌套,并作为第一个诺言的.then),但是没有运气。

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

toby_liao 回答:嵌套诺言:背对背做两个诺言,传递价值

您的new Promise回调函数中参数不匹配。第二个参数与userinput无关,但是是提供给您的拒绝回调(以防您需要)。通过将其命名为userinput,您将无法访问userinput的实际值,因为该值在其上一行传递了。

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

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

,

检查此代码段。希望这会帮助你。提示将自行处理用户输入。因此,当您收到输入时,请执行ajax调用并获取服务器响应。就您所希望的以及据我了解您的问题而言,该方法都是有效的。

    const { app,BrowserWindow } = require('electron')
    const path = require('path')
    const prompt = require('electron-prompt'); // assume that this is what you use 
    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; 

    let mainWindow

    function createWindow() {

    prompt({
        title: 'Prompt example',label: 'License Key:',value: 'xxxx-xxxx-xxxx-xxxx',inputAttrs: {
        type: 'Key'
        },type: 'input'
    })
        .then((r) => {
        if (r === null) {
            console.log('user cancelled');
        } else {
            var data = {key: r}; // accepting the user input
            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true; 
            xhr.addEventListener("readystatechange",function () {
            if (this.readyState === 4) {
                console.log(this.responseText)
                console.log(JSON.parse( this.responseText).status===1?'License complete':'Re enter a valid key')// key validation with the server response
            }
            });

            xhr.open("POST","https://76c6d974-0305-4a40-b499-6b3efee4938f.mock.pstmn.io/license");
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
            xhr.setRequestHeader("Cache-Control","no-cache");  

            xhr.send(JSON.stringify( data));
        }
        })
        .catch(console.error);


    mainWindow = new BrowserWindow({
        width: 800,height: 600,webPreferences: {
        preload: path.join(__dirname,'preload.js')
        }
    })

    mainWindow.loadFile('index.html')

    mainWindow.on('closed',function () { 
        mainWindow = null
    })
    } 
    app.on('ready',createWindow)

祝你好运!投票,如果这有助于其他人更容易找到它。

本文链接:https://www.f2er.com/3144877.html

大家都在问