如何在执行后续代码之前先执行函数调用?

时间:2017-01-21 07:00:01

标签: javascript jquery ajax

我正在尝试通过构建一个随机的报价机来学习JS,但这个问题一直困扰着我。我看到了其他的答案,但由于缺乏背景,我真的无法理解它们。任何帮助将不胜感激。代码是:

$(document).ready(function () {


$("#btn").click(function () {
getQuote();                 //This should execute first, then the next lines
var quoteData = jSonify();
var quote = quoteData[0];
var author = quoteData[1];
console.log(quote);
console.log(author);
console.log("Button Clicked");//This Should execute last.
});

//Get them quotes
function getQuote() {
    $.ajax({
        url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
        type: 'GET',
        data: {},
        datatype: 'json',
        success: function (data) { jSonify(data); },
        error: function (err) { alert(err); },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("X-Mashape-Authorization", "qKPbfOzWKemsh2qi30QgbOA1WufXp1ok1NsjsnAkvh6yVJfaAk");
        }
    });
}

//Convert to jSon
function jSonify(rawData) {
    var jSonified = jQuery.parseJSON(rawData);
    var quote = jSonified.quote;
    var author = jSonified.author;
    console.log(quote);
    console.log(author);
    return [quote, author];
}});

2 个答案:

答案 0 :(得分:2)

当JavaScript运行下一行getQuote()时,

var quoteData = jSonify();将无法完成。这是因为它内部有一个$.ajax调用,这可能需要很长时间才能完成。

在调用getQuote方法中的success方法之前,

$.ajax将无法完成。

所以你需要做的是将回调传递给getQuote,如下所示:

$("#btn").click(function () {
    getQuote(function() {
        var quoteData = jSonify();
        var quote = quoteData[0];
        var author = quoteData[1];
        console.log(quote);
        console.log(author);
        console.log("Button Clicked");
    });
});

//Get them quotes
function getQuote(done) {
    $.ajax({
        url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
        type: 'GET',
        data: {},
        datatype: 'json',
        success: function (data) { jSonify(data); done(); }, // Call the callback!
        error: function (err) { alert(err); },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("X-Mashape-Authorization", "qKPbfOzWKemsh2qi30QgbOA1WufXp1ok1NsjsnAkvh6yVJfaAk");
        }
    });
}

只有在ajax实际完成后才会调用回调。一旦被调用,其余的计算将会发生。

答案 1 :(得分:1)

您可以稍后嵌入在ajax成功中被称为语句

$(document).ready(function () {


$("#btn").click(function () {
getQuote();                 //This should execute first, then the next lines

});

//Get them quotes
function getQuote() {
    $.ajax({
        url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
        type: 'GET',
        data: {},
        datatype: 'json',
        success: function (data) {          
            var quoteData = jSonify(data);
            var quote = quoteData[0];
            var author = quoteData[1];
            console.log(quote);
            console.log(author);
            console.log("Button Clicked");//This Should execute last.
        },
        error: function (err) { alert(err); },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("X-Mashape-Authorization", "qKPbfOzWKemsh2qi30QgbOA1WufXp1ok1NsjsnAkvh6yVJfaAk");
        }
    });
}

//Convert to jSon
function jSonify(rawData) {
    var jSonified = jQuery.parseJSON(rawData);
    var quote = jSonified.quote;
    var author = jSonified.author;
    console.log(quote);
    console.log(author);
    return [quote, author];
}});