我对使用 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
最佳答案
你永远无法从 Promise 中返回
一个值,因为它可能还没有到达。您只能返回另一个 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
函数需要返回
一个promise,它目前不返回任何内容。为什么 this.data
被定义,但没有作为参数传递给回调,我不确定;但即使您确实将其分配给全局 requestData
变量,该值也会被 then
的本地 requestData
变量(命名参数)遮盖回调。
理想情况下,它应该看起来
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
});
关于javascript - 从 Promise 返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25308841/