【问题标题】:How to return the data from a promise如何从承诺中返回数据
【发布时间】:2016-12-08 00:17:19
【问题描述】:

我有这样的功能

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);
});

但是,结果的内容是未定义的。

我是否错误地使用了延迟逻辑?那么正确的方法是什么?

【问题讨论】:

  • 尝试使用deferred.resolve 而不是resolveWith
  • 你为什么使用promise? Promise 适用于异步逻辑,但您的代码中没有任何异步内容。
  • @abl 你的意思是我可以做 var index = getIndex("Hellow World") 然后做 alert(result) 完全没有问题吗?
  • 可以,但是getIndex 函数可以更简单,根本不需要使用promise。 See this snippet
  • 真的有 deferred.resolveWith 方法。我从来没有听说过。

标签: javascript jquery jquery-deferred


【解决方案1】:

几个“问题”。

  1. 无论选择使用resolveWith,其语法都将数组作为第二个参数,而不是对象。

  2. 似乎试图获取具有匹配文本的每个选项的索引。在下拉菜单中显示具有相同文本的选项可能是不寻常的

  3. 以下修改后的代码示例解析了 deferred once,并显示了传递给 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>

【讨论】:

  • 在同步操作中使用 Promise 有什么意义?这只会使原本简单的代码复杂化。 getIndex() 也可以直接返回结果——不涉及任何承诺。
  • @jfriend00 我提出的问题是询问如何让延迟的工作完全发挥作用,使用捏造的例子。下拉菜单中的“大家好”?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
  • 2018-05-16
  • 2020-01-08
相关资源
最近更新 更多