客户端Javascript回调的行为是异步的吗?

时间:2018-11-08 15:56:42

标签: javascript asynchronous callback

我编写了这段代码,将thesaurus.com抓取为特定单词的同义词。

function findWord(key, text) {
    var words;
    scrapeSynonyms(key, function(synonyms) {
        words = synonyms;
    });
    console.log(words);
}

function scrapeSynonyms(word, callback) {
    var synonyms = [];
    var content;
    // get content from thesaurus.com
    var url = "http://allorigins.me/get?url=" + 
    encodeURI('https://www.thesaurus.com/browse/') + word;
    $.get(url, function(response) {
        content = response.contents; 
    }).then(function() {
        // isolate unordered list
        var length = "<ul class='css-1lc0dpe et6tpn80'>".length;
        var startIndex,
            endIndex;
        for(var i = 0; i < content.length-length; i++) {
            if(content.substring(i, i + length) == "<ul class=\"css-1lc0dpe 
            et6tpn80\">") {
                startIndex = i;
                for(var j = i; j < content.length-length; j++) {
                    if(content.substring(j, j + 5) == "</ul>") {
                        endIndex = j;
                        break;
                    }
                }
                break;
            }

        }
        content = content.substring(startIndex, endIndex);
        // separate each individual word into array
        length = "class='css-1ruewre etbu2a31'>".length;
        for(var i = 0; i < content.length-length; i++) {
            var start,
                end;
            if(content.substring(i, i+length) == "class=\"css-1ruewre 
etbu2a31\">") {
                start = i+length;
                for(var j = i; j < content.length-length; j++) {
                    if(content.substring(j, j+4) == "</a>") {
                        end = j;
                        break;
                    }
                }
            }
            if(start != null && end != null) {
                synonyms.push(content.substring(start, end));
                start = null;
                end = null;
            }
        }
    });
    callback(synonyms);
}

scrapSynonyms函数工作正常,如果我在其末尾登录“ synonyms”,它将返回具有正确同义词的数组,但是当我从findWord函数执行此操作时,它仅返回记录一个空数组。我试图通过添加回调来解决此问题,但问题仍然存在。我在这里想念东西吗?

0 个答案:

没有答案