将承诺的结果分配给对象

时间:2019-03-08 08:01:32

标签: javascript angular es6-promise angular-promise

我正在尝试使用这段代码来使用带有角度的neo4j数据库。我读了很多关于诺言的书,但我听不懂。我想在我的results数组上分配查询结果,但是它始终为空。

如何从承诺中返回价值?有可能还是我不了解诺言的用法和目的。我检查过的所有教程都只针对console.log使用Promise。

服务

import { Injectable } from '@angular/core';
import * as neo4j_driver from 'neo4j-driver/lib/browser/neo4j-web.min.js';    

@Injectable()
export class Neo4jService {    

  constructor() { }    

  loadNodes(): Object[]{    

    var results = [];    

    const neo4j = neo4j_driver.v1;
    const uri = 'bolt://localhost:7687';
    const user = 'neo4j';
    const password = 'root';
    const driver = neo4j.driver(uri, neo4j.auth.basic(user, password), {maxTransactionRetryTime: 15000});    

    driver.onCompleted = function () {};

    driver.onError = function (error) {
      console.log('Driver instantiation failed', error);
    };    

    var session = driver.session();    

    var query = "START n=node(*) MATCH (n)-[r]->(m) RETURN n,r,m"    

    session
      .run(query)
      .then(function(result) {
        result.records.forEach(function(record) {
          results.push(record._fields);
        });
        session.close();
        driver.close();
      })
      .catch(function(error) {
        console.log(error);
        driver.close();
      });    

      return results;
    }    

}

组件:

import { Component } from '@angular/core';
import {Neo4jService} from './neo4j.service';    

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'show-graph-browser';    

    constructor(private neo4jService:Neo4jService){}    

    ngOnInit() {
        var results = this.neo4jService.loadNodes();
        console.log(results.toString());
    }    

}

0 个答案:

没有答案