Javascript 从setTimeout做出承诺时感到困惑
我是新来的。我写了两个例子: 第一个是:Javascript 从setTimeout做出承诺时感到困惑,javascript,promise,rsvp.js,Javascript,Promise,Rsvp.js,我是新来的。我写了两个例子: 第一个是: new RSVP.Promise(function (resolve, reject) { setTimeout(function () { resolve("HI") }, 3000); }).then(function (result) { console.log(result); }); 如我所料,这个会在3秒钟后打印出“HI”。这是因为“then”等待它,并且只有在承诺达成时才被调用 第二个是: new
new RSVP.Promise(function (resolve, reject) {
setTimeout(function () {
resolve("HI")
}, 3000);
}).then(function (result) {
console.log(result);
});
如我所料,这个会在3秒钟后打印出“HI”。这是因为“then”等待它,并且只有在承诺达成时才被调用
第二个是:
new RSVP.Promise(function (resolve, reject) {
resolve();
}).then(function () {
return RSVP.Promise(function (resolve, reject) {
setTimeout(function () {
resolve("HI")
}, 3000);
});
}).then(function (result) {
console.log(result);
});
我想它也会在3秒钟后打印“HI”。但什么也没发生。我以为第二个“then”会遵守第一个“then”中的承诺
第二个示例有什么问题以及如何修复它?tl;dr
您需要使用new
运算符构造RSVP承诺
固定代码
new RSVP.Promise(function (resolve, reject) {
resolve();
}).then(function () {
// Note the `new` in the next line
return new RSVP.Promise(function (resolve, reject) {
setTimeout(function () {
resolve("HI")
}, 3000);
});
}).then(function (result) {
console.log(result);
}).catch(console.error);
在您的例子中,它没有做任何事情,因为then
处理程序中的承诺创建失败,因为new
没有与之一起使用。因为,then
处理程序抛出了一个异常,所以它返回了一个失败的承诺。这就是为什么下一个then
处理程序也没有执行的原因
当我使用附加的catch
处理程序执行您的原始代码时,正如上面所示,我得到了以下错误
[TypeError:构造“承诺”失败:请使用“新建”运算符,此对象构造函数不能作为函数调用。]
经验法则:在处理承诺时,始终使用
catch
处理程序。在第二个示例中,您有一个函数在then()函数中返回承诺,但该承诺不会暴露于processing then()中,因此当它解决问题时,它不会执行任何操作。然后()实际上返回它自己的承诺,这允许链接工作。在第二个示例中,第二个then()中的结果应该是您在第一个then()中返回的承诺。我在没有RSVP的情况下尝试了它,使用了本机承诺,并且它在chrome Yup上工作,正如第四位用户所说,您确实错过了一个“新的”。在处理代码笔时,我不假思索地修复了它。