【发布时间】:2019-02-27 21:30:49
【问题描述】:
getPosts() 循环遍历一组帖子,构建 LI 并将它们放在 document.body 中。工作正常。
function getPosts(num){
let output ='';
posts.forEach((post, index)=>{
output += `<li>${post.title} (${num})</li>`;
});
document.body.innerHTML += output;
}
createPost() 返回一个等待 3 秒(模拟客户端-服务器延迟)的承诺,向数组添加一个帖子并解析。
function createPost(post){
return new Promise((resolve, reject) => {
setTimeout(()=>{
posts.push(post);
const error = false;
if (error){
reject ('Error happened!');
}else{
resolve();
}
},3000);
});
}
以下按预期工作。返回三个 LI,分别为 (undefined):
createPost ({title: 'Post Three', body: 'Post Three'})
.then(getPosts);
但是当.then里面的getPosts有参数时,不等promise解析就被触发了:
createPost ({title: 'Post Three', body: 'Post Three'})
.then(getPosts(1));
为什么?
【问题讨论】:
-
请使用代码 sn-ps 而不是外部服务的链接
-
除此标记为重复的参考之外的其他参考:How to add promise to event handler、Promise example not working
标签: javascript promise