1

我对使用 Promise 有点陌生,并且在返回对象时遇到了问题。我有以下函数调用 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

4

1 回答 1

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
}); 
于 2014-08-14T14:15:28.147 回答