簡體   English   中英

如何從承諾中返回數據

[英]How to return the data from a promise

我有一些這樣的功能

function getIndex(name) {
    var deferred = $.Deferred();
    var index = 0;
    $("#dropDown option").each(function () {
        if ($(this).text() === name) {
            index = this.index + 1;
            deferred.resolveWith(this, {result: index });
            return deferred.promise();
        }
    });

    deferred.resolveWith(this, { result: index });
    return deferred.promise();
}

然后我這樣調用函數:

getIndex("Hello World").done(function(result) {
alert (result);
});

但是,結果的內容不確定。

我是否在錯誤地使用延期邏輯? 那么正確的方法是什么?

幾個“問題”。

  1. 無論選擇使用resolveWith ,其語法都將數組作為第二個參數,而不是對象。

  2. 似乎正在嘗試獲取具有匹配文本的每個選項的索引。 在下拉菜單中顯示帶有相同文本的選項可能不常見

  3. 以下修改后的代碼示例解析一次deferred,並顯示如何將傳遞給resolve方法的值數組作為單獨的參數傳遞給done回調。

  function getIndex(name) { var deferred = $.Deferred(); var result = []; $("#dropDown option").each(function () { if ($(this).text() == name) { result.push(this.index + 1); } }); deferred.resolveWith(this, result); console.log("result in getIndex: " + result); return deferred.promise(); } getIndex("hello folks and world").done(function(a, b) { console.log("done callback arguments: " + a + ", " + b); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="dropDown"> <option>hello folks and others</option> <option>hello folks and world</option> <option>hello folks and world</option> </select> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM