如何在回调函数中赋值?

Fly*_*Cat 1 javascript

我遇到了一个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 )

}
Run Code Online (Sandbox Code Playgroud)

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

Rod*_*dik 5

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

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

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

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

编辑:

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

例:

project.prototype.getFolder = function(path, callback){
    ...
    ...
    if (typeof(callback) == "function"){
        callback(this.imagePath);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

project.getFolder(path,function(imagePath){
    console.log(imagePath);
});
Run Code Online (Sandbox Code Playgroud)