使用extend关键字防止函数在异步调用完成之前返回

Prevent function to return before async call is finished using the extend keyword

本文关键字:调用 返回 异步 关键字 extend 函数 使用      更新时间:2023-09-26

代码就是这样的。

//Extending a Nativescript module.      
var test = ImageProvider.extend({
  getImage: function(url){
    //async call to get the image from cache
    cacheService.getImage(url,  
      function(image){
         return image
      }, 
      function(error){ 
        return null 
    });
 }
});

如何防止在提供图像之前返回getImage函数?我不喜欢用打字稿或babel来解决这个问题。但如果需要,请提供建议。(也试过babel,打字没有任何运气)我尝试通过设置使用等待和让步:

"android": {"v8Flags": "--expose_gc --use_strict --harmony"} 

在package.json文件中没有成功。

使用成品给出误差的样本

"use strict" 
function onNavigationgTo(args){ 
  yield test(); 
}
function* test(){
  return 1;
}

在我添加yield关键字之前,它可以正常工作。使用收益率得出以下结果。SyntaxError:意外的严格模式保留字File:"unknown"

您想要做的可能不是一个好主意,因为它会在程序加载时阻塞UI。这个问题通常通过回调或promise/自定义任务实现来解决。回调示例:

getImage: function(url, callback){
    //async call to get the image from cache
    cacheService.getImage(url,  
      function(image){
         callback({ image: image, error: null });
      }, 
      function(error){ 
        callback({ image: null, error: error });
    });
 }

然后使用情况将看起来像

ImageProvider.getImage('someurl.png', function(result) {
    if (result.image) {
        // image has successfully downloaded -- good!
    }
    else {
        // handle result.error
    }
});

为此使用ES6 Promises。

var test = ImageProvider.extend({
  getImage: function(url){
    //async call to get the image from cache
    return new Promise(function(resolve,  reject) {
        cacheService.getImage(url,  
          function(image){
             resolve(image);
          }, 
          function(error){ 
            reject(error);
        });
    });
 }
});

然后像这个一样使用

test.getImage('http://...').then(function(image) {
    // do stuff
});

所有主流浏览器都支持本机承诺。。IE除外(边缘支持)。如果你想要更广泛的浏览器支持,我建议你使用bluebird。