从setTimeout做出承诺时感到困惑

时间:2015-12-01 06:22:08

标签: javascript promise rsvp.js

我是Promise的新手。我写了两个例子:

第一个是:

new RSVP.Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve("HI")
    }, 3000);
}).then(function (result) {
    console.log(result);
});

这个将打印出来" HI"在我预料的3秒后。这是因为"然后"等待它,只有在承诺解决时才会被召唤。

第二个是:

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);
});

我认为它也会打印" HI" 3秒后但什么都没发生。我想第二个"然后"将在第一个"然后"等待承诺。

第二个例子有什么问题以及如何修复它?

2 个答案:

答案 0 :(得分:6)

<强> TL;博士

您需要使用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处理程序中的promise创建失败,因为new没有使用它。因为then处理程序抛出了异常,所以它返回了一个失败的promise。这就是为什么下一个then处理程序也没有执行。

当我附加catch处理程序执行原始代码时,如上所示,我收到以下错误。

  

[TypeError:未能构建&#39;承诺&#39;:请使用&#39; new&#39;运算符,此对象构造函数不能作为函数调用。]

经验法则:在处理承诺时始终使用catch处理程序。

答案 1 :(得分:0)

在你的第二个例子中,你有一个函数在then()函数内部返回一个promise,但是这个promise没有暴露给进程then()所以当它解析时,它没有任何动作可以执行。然后()实际上返回它自己的承诺,这允许链接工作。在第二个例子的情况下,第二个then()的结果应该是你在第一个然后返回的Promise()

相关问题