Javascript函数并返回JSON

时间:2015-11-22 03:29:52

标签: javascript node.js function

#1返回JSON对象时,#2返回undefined。

如何以JSON格式返回数据并访问其属性(如data.username或data.email)?

1

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    useLibrary  'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.example.rohan.weatherapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
repositories { mavenCentral() }
dependencies {
    compile 'com.facebook.android:facebook-android-sdk:4.7.0'
    compile files('libs/aerismaps-1.1.1.jar')
    compile files('libs/aeris-android-lib-1.1.1.jar')
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
}
dependencies {
    compile 'com.android.support:design:23.+'
}

dependencies {
    compile 'com.google.android.gms:play-services:6.5.87'
}

dependencies {
    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'org.apache.httpcomponents:httpclient:4.5'
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'org.apache.httpcomponents:httpclient:4.5'
}

2

function username() {
    user.where('id', req.id).fetch().then(function (data) {
      data = data.toJSON();
      console.log(data);
    });
  }

  var adminJSON = username();

1 个答案:

答案 0 :(得分:1)

这是因为在函数返回之前你是控制台记录adminJSON。该函数正在运行异步。

您需要将用户名回调函数作为参数传递,使用异步库或用户名返回承诺。