1

我的callback功能有问题

project.prototype.getFolder = function(path){

    this.imagePath;
    var instance = this;

    function getImage(image, callback) {
       var it = function(i){
         codes.....
         //I am sure variable image is not null
                  callback(image);

         codes....
        }
    }

   // function to get the image
   getImage(image, function (img) {
        instance.imagePath = img;
   });

   //it outputs undefined...
   console.log(this.imagePath )

}

我想将值分配给函数this.imagePath内部callback,但似乎我得到undefined了我的情况。我确定我传递image了有效的变量,但我仍然一无所获。任何人都可以提供小费吗?非常感谢!

4

2 回答 2

5

您的代码可能是异步的,因此回调函数运行需要时间。此时,虽然您的返回值仍未设置,但您正在尝试打印出变量。

基本上即使代码本身是在回调之后编写的,它也可能在它之前运行。

这可能是您的问题,因此您应该仅在调用回调后尝试访问此值:

   // function to get the image
   getImage(image, function (img) {
        instance.imagePath = img;
        console.log(instance.imagePath);
   });

编辑:

为了将异步参数作为 getFolder 的返回值取回,您应该向 getFolder 传递一个回调函数;

例子:

project.prototype.getFolder = function(path, callback){
    ...
    ...
    if (typeof(callback) == "function"){
        callback(this.imagePath);
    }
}

用法:

project.getFolder(path,function(imagePath){
    console.log(imagePath);
});
于 2013-05-02T19:18:06.657 回答
0

您分配 imagePath,但尝试访问 validImagePath。尝试 :

 console.log(this.imagePath)

而且我不明白你为什么 this.imagePath;一开始就有。可能你想写:

this.imagePath = path;

?

于 2013-05-02T19:13:03.583 回答