从承诺中返回对象

时间:2014-08-14 13:09:23

标签: javascript jquery promise spservices

我对使用promises有点新意,并且在返回对象时遇到问题。我有以下函数调用SPServices从列表中检索一个项目。我知道SPService调用正在返回列表项,但返回的数据是未定义的:

$('.support-View').on('click', function () {
    var thisID = $(this).data("id");
    var message = getOneDetails(thisID);
    console.log("This Data  : " + message); //<-- Comes back undefined
    $.when(message).done(function() {
        thisMessage = message;
        viewRequestDialog(thisID, message);
    });
});

getOneDetails函数如下所示:

function getOneDetails (thisID, viewtype) {

var CAML = '<Query><Where><Eq><FieldRef Name="Title" /><Value Type="Text">' + thisID + '</Value></Eq></Where></Query>';
var list = 'Support Requests';

var requestsPromise = $().SPServices.SPGetListItemsJson({
    listName: list,
    CAMLQuery: CAML,
    includeAllAttrs: true
});

$.when(requestsPromise).done(function() {
    requestData = this.data;
    console.log(this.data); //<---- Data is defined here

    })
    .then(function(requestData) {
    console.log(requestData); //<---- But undefined here
    return requestData;
}); 

}

我确定我错过了一些简单的东西,但是我如何简单地从promise函数返回对象? TIA

1 个答案:

答案 0 :(得分:5)

你永远不能return来自承诺的价值,因为它可能还没有到达。对于根据第一个promise的结果计算的值,您只能返回另一个promise。您的第一个代码段需要如下所示:

$('.support-View').on('click', function () {
    var thisID = $(this).data("id");
    var messagePromise = getOneDetails(thisID);
    messagePromise.done(function(message) {
        console.log("This Data  : " + message); // <-- Comes back as an argument
                                                //     to the callback
        // thisMessage = message; // Don't ever do this. Global variables are
                                  // useless when you don't know *when* they
                                  // will contain a value. If you need to store
                                  // something, store the `messagePromise`.
        viewRequestDialog(thisID, message);
    });
});

您的getOneDetails函数需要return一个承诺,它目前不会返回任何内容。为什么this.data被定义,但没有作为参数传递给回调我不确定;但即使您将其分配给全局requestData变量,该值也会被requestData回调的本地then变量(命名参数)遮蔽。

理想情况下,它应该看起来

return requestsPromise.then(function(requestData) { /*
^^^^^^ notice the return! */
    console.log(requestData); // <---- Data is given as an argument
    return requestData;
});

但你可能需要做

return requestsPromise.then(function() { // again, return the result of the call
    var requestData = this.data; // take it from wherever (unsure what `this` is)
//  ^^^ local variable
    console.log(requestData); // <-- Data is defined here
    return requestData; // and can be returned to resolve the promise with
});