我最近一直在尝试学习 Promise,但是遇到了障碍?任何建议:你能告诉我,我在这里做错了什么吗?
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();
最佳答案
您的代码中有很多拼写错误。
promise
应该是Promise
,大写P
printString("C")
应为printstring("C")
Math.floor(Math.random() * 100) + 1;)
应该是Math.floor(Math.random() * 100) + 1);
如果您想观察 setInterval
与 Promise
在这种情况下如何工作,请增加其延迟(尽管它适用于任何值)。
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();
请注意,避免使用 document.write(string);
,这实际上是一种将内容放置到网站的旧式方式。请改用 innerHTML
或 textContent
之类的内容。在这种特殊情况下,您可以将该行替换为 document.body.textContent += string;
。
关于JavaScript promise 初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50782208/