【问题标题】:JavaScript Promise not executing thenJavaScript Promise 不执行然后
【发布时间】:2014-11-04 22:39:33
【问题描述】:

我正在尝试在以下 JavaScript 代码中实现一个承诺,但是由于某种原因,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;

【问题讨论】:

    标签: javascript es6-promise


    【解决方案1】:

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

    代替:

    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
    }
    

    与其尝试访问承诺范围内的process 变量,不如为您的流程承诺正确设置then

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

    【讨论】:

    • 太棒了,谢谢:) 而且我了解 var response = response 我只是把它放在那里以防它没有正确拾取。但现在我发现没有意义!
    猜你喜欢
    • 2018-07-21
    • 2017-04-22
    • 2017-12-05
    • 1970-01-01
    • 2018-12-31
    • 2013-04-03
    • 2018-04-18
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多