Andy Brunner
Andy Brunner

Reputation: 173

Need some help on yield (and promises?)

For a client Node.js application, I should "wait" for the completion of an http.request, e.g,

console.log('Before http request')
responseData = x.exec(parms)
console.log('Process data')

Module x:
exports.exec = function exec (params) {
  x = https.request(xxxx, function() {
    x.on('data' ...
    x.on('end'...
      return (returnData)
  }  
}

If possible, it should be done without using any co() or other external modules. I have read all sorts of manuals, listen to a bunch of tutorials and tried all sorts of "yield" and function* combinations, but I just don't get it :(

Anyone willing to help a yield-newbie?

Upvotes: 0

Views: 49

Answers (2)

jbpark
jbpark

Reputation: 127

You use generators to 'yield' a promise so that the generator will stop running until that promise has been resolved or rejected. Here is an example using generator + promise for async operation:jsfiddle

function runGenerator(gen) {
    const it = gen();
    let ret;
    (function iterate(val) {
        ret = it.next(val);
        if (!ret.done) {
            if (ret.value instanceof Object && "then" in ret.value) {
                ret.value
                    .then(iterate)
                    .catch((err) => {
                        it.throw(err);   
                    });
            } else {
                setTimeout(function() {
                    iterate(ret.value);
                }, 0);
            }
        }
    })();
}

function myPromise(){
    //Do Async Operation
    return new Promise((res, rej) => {
    res('Result from Async Operation');
  })
}

runGenerator(function*(){
    const myVal = yield myPromise();
  //Generator waits until promise is resolved or rejected
  alert(myVal);
});

Upvotes: 0

Ediruth
Ediruth

Reputation: 168

You cannot use the instruction "return" in an asynchronous function. Instead of doing "return (returnData)", make a callback "callback(status, code, returnData)" or simply "callback(returnData)".

console.log('Before http request')
responseData = null; //Just declaration
x.exec(params, function(status, data) {
    responseData = data;//You can check status to see if all happened fine
}
console.log('Process data')

Module x:
exports.exec = function exec (params, callback) {
    x = https.request(xxxx, function() {
        x.on('data' ...
        x.on('end'...
          callback(1, returnData); // you can made an x.on('error'... method where statuse can be 0
        }  
    }
}

Upvotes: 1

Related Questions