Druxtan
Druxtan

Reputation: 1329

Dart get back value of function

I'm trying to learn Dart by my self, but I come from C and I a bit confused...

I'm doing this :

import 'dart:io';
import 'dart:async';
import 'dart:convert';

Future <Map>    ft_get_data()
{
    File    data;

    data = new File("data.json");
    return data.exists().then((value) {
        if (!value)
        {
            print("Data does no exist...\nCreating file...");
            data.createSync();
            print("Filling it...");
            data.openWrite().write('{"index":{"content":"Helllo"}}');
            print("Operation finish");
        }
        return (1);
    }).then((value) {
        data.readAsString().then((content){
            return JSON.decode(content);
        }).catchError((e) {
            print("error");
            return (new Map());
        });
    });
}

void    main()
{
    HttpServer.bind('127.0.0.1', 8080).then((server) {
        print("Server is lauching... $server");
        server.listen((HttpRequest request) {
            request.response.statusCode = HttpStatus.ACCEPTED;
            ft_get_data().then((data_map) {
                if (data_map && data_map.isNotEmpty)
                    request.response.write(data_map['index']['content']);
                else
                    request.response.write('Not work');
            }).whenComplete(request.response.close);
        });
    }) .catchError((error) {
        print("An error : $error.");
    });
}

I'm trying to get back the new Map, and as you can guess, it doesn't work and I get the 'Not work' msg. While when the code was in same function, it worked...

Please, could you help me ?

And, there a pointer system as C ?

void function(int *i)
{
    *i = 2;
}

int main()
{
    int i = 1;
    function(&i);
    printf("%d", i);
}
// Output is 2.

Thank you for your help.

Final code :

import 'dart:io';
import 'dart:async';
import 'dart:convert';

Future<Map> ft_get_data()
{
    File    data;

    data = new File("data.json");
    return data.exists()
    .then((value) {
        if (!value) {
            print("Data does no exist...\nCreating file...");
            data.createSync();
            print("Filling it...");
            data.openWrite().write('{"index":{"content":"Helllo"}}');
            print("Operation finish");
        }
    })
    .then((_) => data.readAsString())
    .then((content) => JSON.decode(content))
    .catchError((e) => new Map());
}

void        main()
{
    HttpServer.bind('127.0.0.1', 8080)
    .then((server) {
        print("Server is lauching... $server");
        server.listen((HttpRequest request) {
            request.response.statusCode = HttpStatus.ACCEPTED;
            ft_get_data()
            .then((data_map) {
                if (data_map.isNotEmpty)
                    request.response.write(data_map['index']['content']);
                else
                    request.response.write('Not work');
            })
            .whenComplete(request.response.close);
        });
    })
    .catchError((error) {
        print("An error : $error.");
    });
}

Upvotes: 2

Views: 298

Answers (3)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657118

After a brief look I would say you need

Future<Map> ft_get_data() {
  ...
  return data.exists() ...
  ...
}

and use it like

server.listen((HttpRequest request) {
  request.response.statusCode = HttpStatus.ACCEPTED;
  ft_get_data().then((data_map) {
    if (data_map && data_map.isNotEmpty) request.response.write(
        data_map['index']['content']); 
    else 
        request.response.write('Not work');
    request.response.close();
  });
});

A return inside a then doesn't return from ft_get_data but only from then If an async call is involved you can't continue if it was sync, it's then async all the way down.

Upvotes: 1

grohjy
grohjy

Reputation: 2149

I tried to reconstruct your code to "readable" format. I haven't test it, so there might be errors. For me the code is much easier to read if .then() are not nested. Also it helps reading, if .then() starts a new line.

import 'dart:io';
import 'dart:async';
import 'dart:convert';

Future <Map>ft_get_data()
{
    File data;

    data = new File("data.json");
    data.exists() //returns true or false
    .then((value) { // value is true or false
        if (!value) {
            print("Data does no exist...\nCreating file...");
            data.createSync();
            print("Filling it...");
            data.openWrite().write('{"index":{"content":"Helllo"}}');
            print("Operation finish");
        }
    }) // this doesn't need to return anything
    .then((_) => data.readAsString()) // '_' indicates that there is no input value, returns a string. This line can removed if you add return data.readAsString(); to the last line of previous function.
    .then((content) => JSON.decode(content)); // returns decoded string, this is the output of ft_get_data()-function
//    .catchError((e) { //I believe that these errors will show in main-function's error
//      print("error");
//    });
}

void    main()
{
    HttpServer.bind('127.0.0.1', 8080)
    .then((server) {
        print("Server is lauching... $server");
        server.listen((HttpRequest request) {
            request.response.statusCode = HttpStatus.ACCEPTED;
            ft_get_data()
            .then((data_map) {
                if (data_map && data_map.isNotEmpty)
                    request.response.write(data_map['index']['content']);
                else
                    request.response.write('Not work');
            })
            .whenComplete(request.response.close);
        });
    }) 
    .catchError((error) {
        print("An error : $error.");
    });
}

Upvotes: 1

tatumizer
tatumizer

Reputation: 31

you cannot insert one then() into the other. Need to chain them. Otherwise, return JSON.decode(data) returns to nowhere (main event loop) instead of previous "then" handler

Upvotes: 1

Related Questions