# all files / src/js/base/core/ async.js

53.33% Statements 8/15
100% Branches 0/0
37.5% Functions 3/8
53.33% Lines 8/15

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    481×

    2×

    2×
    1×
    1×

    1×
    1×
    1×

     import $ from 'jquery';

    /**
     * @method readFileAsDataURL
     *
     * read contents of file as representing URL
     *
     * @param {File} file
     * @return {Promise} - then: dataUrl
     */
    export function readFileAsDataURL(file) {
      return $.Deferred((deferred) => {
        $.extend(new FileReader(), {
          onload: (e) => {
            const dataURL = e.target.result;
            deferred.resolve(dataURL);
          },
          onerror: (err) => {
            deferred.reject(err);
          }
        }).readAsDataURL(file);
      }).promise();
    }

    /**
     * @method createImage
     *
     * create `<image>` from url string
     *
     * @param {String} url
     * @return {Promise} - then: $image
     */
    export function createImage(url) {
      return $.Deferred((deferred) => {
        const $img = $('<img>');

        $img.one('load', () => {
          $img.off('error abort');
          deferred.resolve($img);
        }).one('error abort', () => {
          $img.off('load').detach();
          deferred.reject($img);
        }).css({
          display: 'none'
        }).appendTo(document.body).attr('src', url);
      }).promise();
    }