.done()无法读取undefined的属性

时间:2016-02-27 17:39:01

标签: javascript promise

以下代码返回'无法读取属性'已完成'未定义的'。我希望function2在function1完成时运行:

function1 = function() {
    console.log("hi");
}
function1();

function1().done(function2);

编辑: 不确定我是否这样做是正确的,但我尝试了承诺并且那也没有成功:

var p = new Promise(function(resolve, reject) {


    var test = window.location.search.substring(1) + ".html";
    console.log(test);

    $("#main-content").load(test);

    if($("#main-content") != null) {
        resolve('Success!');
        function2();
    }
    else {
        reject('Failure!');
    }
});

function2确实运行,但不是异步。

3 个答案:

答案 0 :(得分:1)

您不需要将function2绑定到function1以确保它已完成;代码线性执行。所以先执行function1:

var function1 = function() {
    alert('Observe that I, function1, execute before the lowly function2');
}

var function2 = function() {
    document.getElementById("yourElement").className = "changeColor";
}

function1();
function2();

要看到它的实际效果:

https://jsfiddle.net/ktoeon2f/1/

*注意:我不知道为什么你的延期没有像你期望的那样工作;您必须分享更多以前的代码。 *

编辑1:此处找到OP的具体解决方案:

jQuery: Changing the CSS on an element loaded with ajax?

答案 1 :(得分:0)

如果你想在执行function1之后立即执行function2,你可以按照以下步骤执行:

function1();
function2();

(这是因为function1没有在他内部运行任何异步操作)

答案 2 :(得分:0)

  

我想在function1完成时运行function2:

您需要的是回叫功能。你可以这样做

public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
{
    string Output = "";
    const string fromCurrency1 = "USD";
    const string toCurrency1 = "INR";
    const double amount1 = 2000;

    // Construct URL to query the Yahoo! Finance API
    const string urlPattern = "http://finance.yahoo.com/d/quotes.csv?s={0}{1}=X&f=l1";
    string url = string.Format(urlPattern, fromCurrency1, toCurrency1);

    // Get response as string
    string response = new WebClient().DownloadString(url);

    // Convert string to number
    double exchangeRate =
        double.Parse(response, System.Globalization.CultureInfo.InvariantCulture);

    // Output the result
    Output=(amount1*exchangeRate).ToString();

    return Output;
// Ref: http://salmankavish.blogspot.in/2016/02/currency-converter-using-c.html
}