如何在回调函数中赋值? [英] How to assign value in the callback function?

查看:953
本文介绍了如何在回调函数中赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了回调问题功能

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 函数,但在我的情况下似乎我得到 undefined
我确定我传递了有效的 image 变量,但我仍然没有得到任何结果。任何人都可以提供小费吗?非常感谢!

I want to assign the value to this.imagePath inside the callback function, but it seems I am getting undefined in my case. I am sure I pass valid image variable but I am still getting nothing. Can anyone provide a tip? Thanks a lot!

推荐答案

您的代码可能是异步的,因此回调函数需要一段时间才能运行。在这个时候,虽然你的返回值仍然没有设置,你试图打印出变量。

Your code may be asynchronous, hence it takes time for the callback function to run. in this time, while your return value is still not set, you are trying to print out the variable.

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

Basically even though the code itself is written after the callback, it may run before it.

这可能是你的问题,所以你应该尝试在调用回调之后访问这个值:

This is probably your problem, so you should try to access this value only after the callback as been called:

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

编辑:

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

In order to get the asynchronous parameter back as a return value for getFolder, you should pass a callback function to getFolder;

示例:

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

用法:

project.getFolder(path,function(imagePath){
    console.log(imagePath);
});

这篇关于如何在回调函数中赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆