JavaScript Promise 然后没有执行

标签 javascript es6-promise

我试图在以下 JavaScript 代码中实现一个 promise ,但是由于某种原因,process.then 函数实际上从未发生过。谁能明白为什么吗?我已经设置了新的 promise ,并且它按照我使用控制台日志测试的方式执行,但是它从未执行 .then 函数

谢谢

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;

最佳答案

您不应将 process.then() 放在 new Promise() block 中。

而不是:

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

用途:

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

这不会尝试访问 Promise 范围内的 process 变量,而是为您的流程 Promise 正确设置 then

此外,var response = response; 是毫无意义的。它并没有真正向您的代码添加任何内容。

关于JavaScript Promise 然后没有执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26737582/

相关文章:

javascript - JavaScript 中的 &= 运算符用于减少 bool 值

类中的 Javascript 数组属性仅在从函数调用时返回

javascript - 当await表达式是concat()的参数时,为什么async/await有不同的输出?

asynchronous - 如何将 Promise.all() 与 chrome.storage() 结合使用?

javascript - 通过java API从orientdb调用JS函数

javascript - 如何访问和处理嵌套对象,数组或JSON?

javascript - 在 IE 6 中如何让 float 页脚粘在视口(viewport)底部?

typescript promise 拒绝和 vscode 调试器行为

javascript - 如何使用 vanilla Node.js 运行 500 个请求,其中 20 个并行

javascript - 上传文件的异步验证(React Dropzone + TS)