• Places
    • Home
    • Graphs
    • Prefixes
  • Admin
    • Users
    • Settings
    • Plugins
    • Statistics
  • CPACK
    • Home
    • List packs
    • Submit pack
  • Repository
    • Load local file
    • Load from HTTP
    • Load from library
    • Remove triples
    • Clear repository
  • Query
    • YASGUI SPARQL Editor
    • Simple Form
    • SWISH Prolog shell
  • Help
    • Documentation
    • Tutorial
    • Roadmap
    • HTTP Services
  • Login

13.3 Accessing JavaScript from Prolog
All Application Manual Name SummaryHelp

  • Documentation
    • Reference manual
      • Using SWI-Prolog in your browser (WASM)
        • Accessing JavaScript from Prolog
          • :=/2
          • is_object/1
          • is_object/2
          • js_script/2
          • fetch/3
          • Asynchronous access to JavaScript from Prolog
            • await/2
            • is_async/0
          • JavaScript Promise that can be aborted
    • Packages

13.3.1 Asynchronous access to JavaScript from Prolog

While section 13.3 describes synchronous calls from Prolog to JavaScript, we also need asynchronous calling to implement sleep/1, wait for user input, downloading documents from the web, etc. Asynchronous calling is achieved by yielding from the Prolog virtual machine. This can only be done when Prolog is told to expect that the VM may yield. This is implemented by Prolog.forEach() as described in section 13.2.

[det]await(+Promise, -Result)
Yield the Prolog VM, returning control back to JavaScript. When this is called from Prolog invoked using Prolog.forEach(), execution of await/2 completes when the Promise resolves and Result is unified with the value passed to the Promise.then() method. As an exception to the normal conversion rules, if the result is a single String, it is returned as a Prolog string rather than an atom. When the Promise is rejected await/2 throws an exception. Note that await/2 allows, for example, downloading a URL from Prolog:
?- FP := fetch("test.pl"), await(FP, Response),
   TP := Response.text(), await(TP, T).
FP = <js_Promise>(4),
Response = <js_Response>(5),
TP = <js_Promise>(6),
T = "% :- debug(js) ...".

Calls to await/2 may be asynchronously aborted by calling Prolog.abort() if Promise implements .abort(). See section 13.3.2 for implementing such a promise.

[semidet]is_async
True when we can call await/2 in the current state. This implies Prolog has been called from JavaScript code that is prepared to deal with Prolog yielding and Prolog is not inside a callback from C (WASM).

ClioPatria (version V3.1.1-51-ga0b30a5)