我正在努力从PouchDB GET调用中获取一个值,以便我可以在初始加载页面时在HTML中使用它。我已设法创建数据库,并存储一个很容易的记录,因为他们不要求我等待返回值。
使用Chrome开发工具我可以在PouchDB get调用中断点并看到它返回我需要的数据,但它在我遇到问题的aysnc GET调用之外获取该值。
相关代码如下(IanC答案的更新):
jQuery(document).ready(function () {
// Store note data as object for pass-by-reference
var notesData = {note_text:null, note_rev_id:null};
// Create/get database
var notesDb = null;
try {
notesDb = new PouchDB(notesDbName);
} catch (e) {
console.log(e);
}
// Query for a note entry that has the matching ID
function pouchDbGetNote(dbId, dbObj, noteObj){
dbObj.get(dbId)
.then(function (response) {
returnNoteData(response, noteObj);
}).catch(function (err) {
console.log(err);
});
}
// Return the result of the GET query to a variable that is is
// accessible outside of the aysnc pouchDB GET query.
function returnNoteData(result, noteObj){
// Store the note text in local scope - Used in UI display with Div tag
noteObj.note_text = result.note;
// Store the note revision id in local scope (Need for updating note in db)
noteObj.note_rev_id = result._rev;
}
/*
This gets called and debugging thread moves onto lines below
immediately (notesData is empty at this point) then 'returnNoteData'
gets called a second time but by this time the UI update calls have occurred.
*/
pouchDbGetNote(dbEntryId, notesDb, notesData);
// TODO: Insert the note text into the UI Div, update data attribute on btn with revision id
notesContentInitialValue = notesData.note_text;
console.log('msg@ Init - Note: ' + notesData.note_text);
});
John - 您在为其分配值之前尝试使用noteResult。在dbObj.get Promise解析之前,您的代码到达最后两行。
在值可用之前,您必须等待Promise解析。如果你移动了最后两行(在returnNoteData函数中指定notesContentInitialValue和noteRevisionId,它们将具有值(正如您在调试时看到的那样)。