我正在努力从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);
});
答案 0 :(得分:0)
John-您正在尝试为 noteResult 分配一个值。您的代码到达 dbObj.get 承诺解决之前的最后两行。
在值可用之前,您必须等待Promise解决。如果移动了最后两行(在 returnNoteData 函数内分配了notesContentInitialValue和noteRevisionId),它们将具有值(如调试时所看到的)。