Async / wait replace in Nodejs

I am trying to execute the async / await function in C #, but in node js I found an example , but it gives me an error.

here is the code

function* gotNews(response){    
        console.log("in gotNews");
        str='';
        response.on('data', function (chunk) {
            str += chunk;
        });    
        response.on('end', function () {
              str = JSON.parse(str);
              console.log(str);
              fetchCategories();
        });
        return str;
}


function fetchNews(sourceURL){
        console.log("in fetch news");
             sourceURL = url.parse(sourceURL);
             console.log(sourceURL);
        var options = 
        {
            host: sourceURL.host,
            port: 134,
            path: sourceURL.path,

            method: 'GET',
        };
        var req = http.request(options,yield gotNews);//start request and recive response in gotSources
        req.end();
}

I use the * yield operation, but gives me an error

ErrorC:\Users\Alaa\Desktop\Fluid_layout_with_jQuery_Masonry\1\app.js:198
        var elnewselygat = yield gotNews();
                                 ^^^^^^^
SyntaxError: Unexpected identifier
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3
+4
source share
3 answers

You will need generators and promises to make them as light as async/ await/ Task.

As @Paul stated, generators are a โ€œfuture featureโ€, so you need to go through --harmonyor --harmony-generators. In addition, generators are supported in V8 3.19, which is only found in Node.js 0.11.2 or later.

JavaScript ; , .

+2

: https://github.com/luciotato/waitfor-es6

, , . ( promises)

function * ---- > # async

yield wait.for(fn...) --- > # wait

0

You can use async/awaitwith babel --stage 1 --optional runtime.

0
source

All Articles