JSFiddle - React, Tailwind, and code Playground

by lid0

HTML

<div id="app">
  <pre style="font-size:11px;">
  implement await capabilities for async function call, used as expresion in a directive 
  for example v-if.  
  &lt;div v-if="await(doSomethingAsync,null)"&gt;
    Ok async resolved to true
  &lt;/div&lg;
  
  await needs a "static"reference to a function that accept no arguments
  a default value get be set once per component for a function. 
  in the example above we default to null, untill doSomethingAsync resolve to true/false . 
  
</pre>

  <div class="app">
    <div>
      Waiting for async to return true : <b v-if="await(doSomethingAsyn, null)">WASSAAAA, true </b><b v-else>__________</b>
    </div>

    <div>
      <!-- notice: the default will be ignored, due to memoization -->
      <!-- we use the default null, to "detect" pending state. (promise will resolev to boolean) -->
      <b>async status/response: {{ await(doSomethingAsyn, "blabla is ignored") ?? "pending" }}</b>
    </div>



  </div>

</div>

CSS

ul {
  float:left;
}

.app{
  border:1px solid gray;
  border-radius:10px;
  background:#cfc;
  padding:10px;
}

JavaScript

//author: lidlanca 2021 march 21

import { createApp, ref } from "https://unpkg.com/[email protected]/dist/vue.esm-browser.js";


const app = createApp({
  setup() {

    const awaitPromiseMap = new WeakMap();

    function awaitPromise(func, defaultValue) {

      if (!awaitPromiseMap.has(func)) {
        var r = ref(defaultValue);
        console.log(func)
        var p = func()
        awaitPromiseMap.set(func, r)
        p.then(function(v) { // update ref to resolved value
          r.value = v
        });
      }
      return awaitPromiseMap.get(func).value

    }

    /**
    doSomethingAsync - will do something and resolve after 3 seconds.
    */
    async function doSomethingAsyn() {
      return new Promise(
        function(r) {
          setTimeout(function() {
            console.log("resolved")
            r(true)
          }, 3000)
        })
    }

    return {
      doSomethingAsyn,
      await: awaitPromise,
    };
  }

});

app.mount("#app");