admin管理员组文章数量:1278852
In the following code block only 'first promise' is logged to console. Why is that? I was trying to write a test to figure out how .then()'s execute after .catch() but was surprised when nothing besides the first promise ran. Whats going on here?
function foo() {
return new Promise((resolve, reject) => {
return console.log('first promise')
})
.then(() => console.log('first then'))
.catch(() => console.log('catch block'))
.then(() => console.log('last block'))
.then(() => resolve)
}
foo();
In the following code block only 'first promise' is logged to console. Why is that? I was trying to write a test to figure out how .then()'s execute after .catch() but was surprised when nothing besides the first promise ran. Whats going on here?
function foo() {
return new Promise((resolve, reject) => {
return console.log('first promise')
})
.then(() => console.log('first then'))
.catch(() => console.log('catch block'))
.then(() => console.log('last block'))
.then(() => resolve)
}
foo();
Share
Improve this question
asked May 10, 2017 at 14:52
sunnyharrissunnyharris
1151 gold badge1 silver badge6 bronze badges
1
- 5 You never resolve nor reject initial promise. – Yury Tarabanko Commented May 10, 2017 at 14:55
2 Answers
Reset to default 6As Yury said, you're not resolving the promise, simply returning a log.
https://jsfiddle/k7gL57t3/
function foo() {
var p1 = new Promise((resolve, reject) => {
resolve("Test");
})
p1.then(() => console.log('first then'))
.then(() => console.log('last block'))
.then(() => resolve)
.catch(() => console.log('catch block'));
}
foo();
I believe it's because your then
chain does not have closure to resolve
inside of the Promise callback. Try this:
function foo() {
return Promise.resolve()
.then(() => console.log('first then'))
.catch(() => console.log('catch block'))
.then(() => console.log('last block'));
}
or this if you want to use the Promise constructor:
function foo() {
return new Promise((resolve, reject) => {
console.log('first promise');
return resolve();
})
.then(() => console.log('first then'))
.catch(() => console.log('catch block'))
.then(() => console.log('last block'));
}
本文标签: javascriptPromisethen not executingStack Overflow
版权声明:本文标题:javascript - Promise.then not executing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741261345a2367683.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论