Reputation: 87
I have been trying to learn promises recently, but I am hitting a roadblock? any suggestions: Can you tell me, what I am doing wrong here?
function printstring(string) {
return new promise( function (resolve,reject) {
setTimeout(function () {
document.write(string);
resolve();
}, Math.floor(Math.random() * 100) + 1;)
})
}
function printall() {
printstring("A")
.then(function () { return printString("C"); })
}
printall();
Upvotes: 0
Views: 94
Reputation: 14462
You have a lot of typos in your code.
promise
should be Promise
with capital P
printString("C")
should be printstring("C")
Math.floor(Math.random() * 100) + 1;)
should be Math.floor(Math.random() * 100) + 1);
If you want to observe how setInterval
together with Promise
works in this case then increase its delay (although it works just fine with any value).
function printstring(string) {
return new Promise( function (resolve,reject) {
setTimeout(function () {
document.write(string);
resolve();
}, Math.floor(Math.random() * 1000) + 1);
})
}
function printall(){
printstring("A")
.then(function () { return printstring("C"); })
}
printall();
Just a small note, avoid using document.write(string);
, it is really an old style way of placing content to your website. Instead use something like innerHTML
or textContent
. In this particular case, you could replace that line with document.body.textContent += string;
.
Upvotes: 2
Reputation: 282
function printstring(string) {
return new Promise( (resolve, reject)=> {
setTimeout(
() => {
console.log(string);
resolve();
}, Math.floor(Math.random() * 100) + 1);
})
}
function printall() {
printstring("A")
.then(function () {
return printstring("C");
})
}
printall();
Better use Es6 arrow functions.this makes your code cleaner.
i was using node so replaced document.write with console.log
Upvotes: 1
Reputation: 9095
function printString(string){
return new Promise(function(resolve, reject){
setTimeout(function(){
document.write(string);
resolve();
}, Math.floor(Math.round() * 100) +1)
})
}
function printAll(){
printString("Test").then(function(res){
printString("<br>sample<br>");
})
}
printAll();
promise should be Promise (Start with Capital P) see doc Promise in JavaScript
Upvotes: 0
Reputation: 116
When creating an instance of Promise, you're doing it in lower case, should be new Promise
not new promise
.
Upvotes: 0