Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  153] [ 3]  / answers: 1 / hits: 16448  / 7 Years ago, wed, january 17, 2018, 12:00:00
function recursiveAsyncReadLine(){
rl.question(name : , function(answer) {
if(answer===exit){
rl.close();
}
var kitty = new Kitten({name : answer});
kitty.save(function(err, kitty){
if(err){
throw err;
}
kitty.speak();
Kitten.find(function(err, kittens){
if(err){
throw err;
}
console.log(kittens);
recursiveAsyncReadLine();
});
});
});
}


I tried to change the code above with promise.



function recursiveAsyncReadLine(){
rl.question(name: )
.then((answer)=>{
if(answer===exit){
rl.close();
}
var kitty = new Kitten({name : answer});
return kitty.save();
})
.then((kitty)=>{
kitty.speak();
return Kitten.find();
})
.then((kittens)=>{
console.log(kittens);
recursiveAsyncReadLine();
})
.catch((err)=>{
throw err;
});
}


But it doesn't work with a message




TypeError: Cannot read property 'then' of undefined




The error occured at the first 'then' statement.



I'm not certain that I understood Promise correctly. Where did I make a mistake?


More From » javascript

 Answers
4

You have misunderstood the promise. Your r1.question function does not return a promise at present. It rather accepts a callback function and then you continue async execution



In Order to promisify it, you can create a wrapper function to r1.question as follows:---



var promisifiedr1 = new Promise(function(resolve, reject){
rl.question(name: , function(answer){
resolve(answer);
})
});

promisifiedr1.then((answer)=>{
if(answer===exit){
rl.close();
}

var promisifiedkitty = new Promise(function(resolve, reject){
var kitty = new Kitten({name : answer});
kitty.save(function(err, kitty){
if(err){
throw err;
}
resolve(kitty);
});

promisifiedkitty.then((kitty)=>{
kitty.speak();
return Kitten.find();
})
.then((kittens)=>{
console.log(kittens);
recursiveAsyncReadLine();
})
.catch((err)=>{
throw err;
});
});

[#55436] Sunday, January 14, 2018, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamaal

Total Points: 515
Total Questions: 102
Total Answers: 107

Location: France
Member since Thu, May 6, 2021
3 Years ago
;