title: How to make a function return a promise if optional callback is not passed?
body: <p>I could come up with </p>
  
  <pre><code> function squareAsync(val, callback) {
  if (callback) {
      setTimeout(() =&gt; {
          if (Math.random() &lt; 0.5) {
              callback(undefined, val * val);
          }
          else {
              callback(new Error('Failed!'));
          }
      }, 2000);
  }
  else {
      return new Promise((resolve, reject) =&gt; {
          setTimeout(() =&gt; {
              if (Math.random() &lt; 0.5) {
                  resolve(val * val);
              }
              else {
                  reject(new Error('Failed!'));
              }
          }, 2000);
     });
   }
  }
  </code></pre>
  
  <p>I found another way for this</p>
  
  <pre><code> function squareAsync1(val, callback) {
  let p = new Promise((resolve, reject) =&gt; {
      setTimeout(() =&gt; {
          if (Math.random() &lt; 0.5) {
              resolve(val * val);
          }
          else {
              reject(new Error('Failed!'));
          }
      }, 2000);
  });
  if (callback) {
      p.then(d =&gt; {
          callback(undefined, d);
      }, e =&gt; {
          callback(e);
      });
   }
  return p;
  }
  </code></pre>
  
  <p>Which one of these is better or there is a more standard and elegant way of doing this? Can we do this using <code>async/await</code>?</p>