简体   繁体   English

从Javascript函数中提取dataURL

[英]Extract dataURL from Javascript function

I have a function that aims to create a dataURL of a file using the FileReader. 我有一个旨在使用FileReader创建文件的dataURL的函数。 Considering this example. 考虑这个例子。

toDataURL(url, callback){
  var xhr = new XMLHttpRequest();
  xhr.open('get', url);
  xhr.responseType = 'blob';
  xhr.onload = function(){
    var fr = new FileReader();
    var test = fr.onload = function(){
      callback(this.result);
    };

    fr.readAsDataURL(xhr.response); // async call
  };

  xhr.send();
}

I want to extract the variable this.result in the inline function as a return variable. 我想将内联函数中的变量this.result提取为返回变量。 It has not acces from other function. 它没有其他功能。 How can I do it? 我该怎么做?

Basicaly, what you want to do is return a value from an async function, you can do this with Promises, and optionally async/await. 基本上,您要做的是从异步函数返回一个值,您可以使用Promises以及可选的async / await来实现。

Check this out: 看一下这个:

 function toDataURL(url, callback) { return new Promise( function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('get', url); xhr.responseType = 'blob'; xhr.onload = function() { var fr = new FileReader(); var test = fr.onload = function() { resolve(this.result) callback(this.result); }; fr.readAsDataURL(xhr.response); // async call }; xhr.onerror = function() { reject('Error); } xhr.send(); }); } const result = await toDataURL('some url'); // or toDataURL('some url').then((result) => { // do something with the result }); 

You could try to use Promise , like this: 您可以尝试使用Promise ,如下所示:

toDataURL(url){
  var promise = new Promise(function (extract) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url);
    xhr.responseType = 'blob';
    xhr.onload = function(){
      var fr = new FileReader();
      var test = fr.onload = function(){
        extract(this.result);
      };

      fr.readAsDataURL(xhr.response); // async call
    };

    xhr.send();
  });

  return promise;
}

(async function () {
  var result = await toDataURL('/someurl');

  console.log(result);
}());

Inside the toDataURL function, we create a promise. toDataURL函数内部,我们创建了一个toDataURL When returning the result, we just need to put it inside extract method. 返回结果时,我们只需要将其放入extract方法中即可。

Then, we create an asynchronous function to use await keyword to get the result directly. 然后,我们创建一个异步函数以使用await关键字直接获取结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM