Edward Tierra Edward Tierra -4 years ago 84
Javascript Question

Prototype.then isn't being used

I've been stumped with promises for awhile: I'm using bluebird Promise within a post request for an asynchronous function, and then using

.then()
to show the results of it and putting it into a
res.json()
. Problem is, I don't see
.then()
being used at all.

var transcribe = function(){
return new Promise(function(resolve, reject){
speech.startRecognition(aux.gsUri, aux.fileType, function(err, operation, res) {
if (err) {
console.error(err);
} else {
operation.on('error', function(err){
console.error(err);
}).on('complete', function(transcript){
var returnAllTranscripts = [];
transcript.forEach(function(block){
returnAllTranscripts.push(block.transcript);
});
return returnAllTranscripts;
});
}
});
})
}
transcribe().then(function(data){ //transcribe() function works
console.log("Now on THEN"); //but not .then(), logging here
res.json(data)
});;

Answer Source

You need to resolve/reject your Promise to hit the then/catch of your promise chain.

var transcribe = function(){
  return new Promise(function(resolve, reject){
    speech.startRecognition(aux.gsUri, aux.fileType, function(err, operation, res) {
      if (err) {
        console.error(err);
        return reject(err); // <-- REJECT ERROR HERE
      } else {
        operation.on('error', function(err){
          console.error(err);
          return reject(err); // <-- REJECT ERROR HERE
        }).on('complete', function(transcript){
          var returnAllTranscripts = [];
          transcript.forEach(function(block){
            returnAllTranscripts.push(block.transcript);
          });
          return resolve(returnAllTranscripts); <-- RESOLVE "THEN" VALUE HERE
        });
      }
    });
  })
}

transcribe().then(function(data){      //transcribe() function works
  console.log("Now on THEN");        //but not .then(), logging here
  res.json(data)
})
.catch(err => console.log(err));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download