story.lpr 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. program story;
  2. {$mode objfpc}
  3. uses
  4. JS, Web, utils;
  5. Function ShowAllDone(aValue : JSValue) : JSValue;
  6. begin
  7. addTextToPage('All done');
  8. end;
  9. Function ShowError(aValue : JSValue) : JSValue;
  10. begin
  11. addTextToPage('Broken: '+TJSError(aValue).Message);
  12. end;
  13. Function HideSpinner(aValue : JSValue) : JSValue;
  14. begin
  15. TJSHTMLElement(document.querySelector('.spinner')).style.SetProperty('display','none');
  16. end;
  17. Function ShowStory(aJSON : JSValue) : JSValue;
  18. function ShowChapters(Chain, currentChapter: JSValue; currentIndex: NativeInt;
  19. anArray: TJSArray): JSValue;
  20. Function FetchNext(aValue : JSValue) : JSValue;
  21. begin
  22. Result:=getJson(String(currentChapter));
  23. end;
  24. Function AddToPage(aChapter : JSValue) : JSValue;
  25. Var
  26. o : TJSObject;
  27. begin
  28. o:=TJSObject(aChapter);
  29. addHtmlToPage(String(o['html']));
  30. end;
  31. begin
  32. Result:=TJSPromise(chain).
  33. _then(@FetchNext).
  34. _then(@AddToPage);
  35. end;
  36. Var
  37. Story : TJSObject;
  38. begin
  39. Story:=TJSObject(aJSON);
  40. addHtmlToPage(String(story['heading']));
  41. Result:=TJSArray(story['chapterUrls']).reduce(@ShowChapters,TJSPromise.resolve(null));
  42. end;
  43. begin
  44. initSlowNetWork;
  45. getJson('story.json').
  46. _then(@ShowStory).
  47. _then(@ShowAllDone).
  48. catch(@ShowError).
  49. _then(@HideSpinner);
  50. end.