简体   繁体   English

JavaScript Promise然后不执行

[英]JavaScript Promise not executing then

I am trying to implement a promise into the following JavaScript code, however the process.then function never actually happens for some reason. 我正在尝试在以下JavaScript代码中实现Promise,但是由于某种原因,process.then函数实际上从未发生过。 Can anyone see why? 谁能看到原因? I have set up the new promise and it executes as I have tested it with the console log, however it never executes the .then function 我已经设置了新的Promise,并且它已经按照控制台日志对它进行了测试,但是它从未执行过.then函数

Thanks 谢谢

function connect() {
    'use strict';
    //User Input
    var query = document.getElementById('query').value;
    //API key & URL
    var apiUrl = 'https://community-wikipedia.p.mashape.com/api.php?action=opensearch&search=' + query + '&limit=20&namespace=0&format=json';
    var apiKey = "xxxxx";


    //While requesting the data from API set the innerHTML to loading.
    //document.getElementById('suggestions').innerHTML='Loading your request...';
    document.getElementById('spin').style.display = 'inline';

    //Process the JSON data
    var process = new Promise(function (resolve, reject) {
        //Method for connecting to API
        var httpRequest = new XMLHttpRequest();

        //Opening the API URL
        httpRequest.open('GET', apiUrl, true);
        httpRequest.setRequestHeader("X-Mashape-Key", apiKey);
        httpRequest.send(null);
        //When state has changed then triggers processResponse function
        httpRequest.onload = function() {
            //Checks the response codes
            if (httpRequest.readyState === 4) {
                //document.getElementById('suggestions').innerHTML='';
                if (httpRequest.status === 200) {
                    var response = JSON.parse(httpRequest.responseText);
                    //Clear any previous results
                    document.getElementById('suggestions').innerHTML = '';
                    //Remove spinner when data is input
                    document.getElementById('spin').style.display = 'none';
                    resolve(response);
                } else {
                    alert('There was a problem with the request');
                    reject('No Good!');
                }
            }
        }
        process.then (function(response) {
            //Set response to response
            var response = response;
            //Grab suggestions div from DOM   
            var suggestions = document.getElementById('suggestions');
            //Create new element UL
            var list = document.createElement('UL');
            //Create new elements for li's
            var newLi, newText;
            //For all the text nodes
            var textNodes = [];
            //For all the li's
            var liList = [];
            //For all the links
            var links = [];
            //For loop to add and append all suggestions 
            for (var i = 0; i < response[1].length; i++) {
                //Replace spaces with underscore
                var setHTML = response[1][i].replace(/\s/g, '_');
                //Creates the appropriate link
                var link = 'http://en.wikipedia.org/wiki/'+setHTML;
                //Create new a elements in array
                links[i] = document.createElement('a');
                //Adds the link to links array
                links[i].href = link;
                //Create new text node with the response from api
                textNodes[i] = document.createTextNode(response[1][i]);
                //Create a new element 'li' into array
                liList[i] = document.createElement('li')
                //Append the response(textnode) to the a in the array
                links[i].appendChild(textNodes[i]);
                //Append the a to the li in the array
                liList[i].appendChild(links[i]); 
                //Append the li to the UL 
                list.appendChild(liList[i]);
            }
            //Append the UL to the suggestions DIV
            suggestions.appendChild(list);
        }  
    )}
)}



function init() {
    'use strict';
    document.getElementById("query").addEventListener("keyup", connect);
}
window.onload = init;

You shouldn't place your process.then() in the new Promise() block. 您不应将process.then()放在new Promise()块中。

Instead of: 代替:

var process = new Promise(function (resolve, reject) {
    // Code
    process.then (function(response) {
       // Code
    }  
)}

Use: 采用:

var process = new Promise(function (resolve, reject) {
    // Code
)}
process.then (function(response) {
    // Code
}

Instead of trying to access a process variable in the promise's scope, this then properly sets a then for your process promise. 而不是尝试访问promise范围内的process变量,而是为您的过程promise设置了一个then

Also, var response = response; 另外, var response = response; is pretty pointless. 毫无意义。 It doesn't really add anything to your code. 它实际上并没有在代码中添加任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM