Little Child Little Child - 4 months ago 11
Javascript Question

Return a promise from a generator function?

So I currently have a promisified function (that returns a promise to another function that calls it) that has some logic that goes like this:

function( param1,param2 ){
if( condition1 ){
return function1();
}

if( condition2 ){
return function2().then(
() => {
// blah blah
return promsie;
}
)
}
}


function1()
and
function2()
are both promisified functions. However, sometimes the
then
chain gets complicated. I would love to move to generators.

is this the right way to port to generators without breaking the outer function which simply expects a promise but does nothing with it:

function(param1,param2){
co(function*(){
if( condition1 ){
let result = yield function1();
this.return( result );
}
if( condition2 ){
let result = yield function2();
this.return( result )
}
});
return Q();
}

Answer

co returns a promise co documentation

co(function*(){
    var myValue;

    if( condition1 ){
         myValue = yield function1(); 
    }
    else if( condition2 ){
        myValue = yield function2();
    }

    return myValue;
})
.then(function(value){
  console.log(value); // will output myValue
})
.catch(...);

So if you want to modify your function you can do the following

function myFunc(param1,param2){
  return co(function*(){
      var myValue;

      if( condition1 ){
           myValue = yield function1(); 
      }
      else if( condition2 ){
          myValue = yield function2();
      }

      return myValue;
  });
}

This way you can use it somewher else

myFunc(param1,param2)
  .then(function(value) {
    console.log(value); // will output myValue
  });
Comments