Does anyone know an elegant way of making this function return the correct value?
It is meant to return 1, since there is one entry of "g_sampleSettingChildName".
I click on a button:Code:function getNumBookmarkFolders() { log('getNumBookmarkFolders() Begin'); var numBookmarkFolders = -1; chrome.bookmarks.search(g_sampleSettingChildName, function(results) { log('callback function begin'); numBookmarkFolders = results.length; log("If we returned here: "+numBookmarkFolders); return numBookmarkFolders; }); log('getNumBookmarkFolders() End'); log("getNumBookmarkFolders() returning: "+numBookmarkFolders); return numBookmarkFolders; }
It shows:Code:<input id="debugShowNumBookmarkFolders" type="button" value="debugShowNumBookmarkFolders" onclick="alert(window.opener.getNumBookmarkFolders());" />
And displays -1 in the alert box. As you can see the getNumBookmarkFolders() function exits before the callback has finished. Is there an elegant way of making getNumBookmarkFolders() wait until the callback has finished?getNumBookmarkFolders() Begin
getNumBookmarkFolders() End
getNumBookmarkFolders() returning: -1
callback function begin
If we returned here: 1
Changing to this:
Just displays:Code:function getNumBookmarkFolders() { var callbackFinished = false; log('getNumBookmarkFolders() Begin'); var numBookmarkFolders = -1; chrome.bookmarks.search(g_sampleSettingChildName, function(results) { log('callback function begin'); numBookmarkFolders = results.length; log("If we returned here: "+numBookmarkFolders); callbackFinished = true; }); while (!callbackFinished) { ; //maybe sleep? } log('getNumBookmarkFolders() End'); log("getNumBookmarkFolders() returning: "+numBookmarkFolders); return numBookmarkFolders; }
getNumBookmarkFolders() Begin
And gets stuck in an infinite loop. The callback never gets executed.
The only way I know of is to nest whatever you want to happen "after" the callback inside the callback (eg you can even pass in a function pointer). Is there some way of waiting for a callback to finish?


LinkBack URL
About LinkBacks



Reply With Quote