Promise.resolve和新Promise(解决)是否可以互换

时间:2015-12-01 06:59:37

标签: javascript node.js promise rsvp.js

我认为Promise.resolvenew Promise(resolve)可以互换。

考虑一下:

一个。

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

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

印刷" HI"正如我所料。

所以我想如果我不需要"拒绝"任何东西。为简单起见,我可以写RSVP.resolve();

但请考虑这个例子:

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

如何使用RSVP.resolve();替换?我试过例如:

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

这会打印其他内容,而不是" HI"。那么可以使用RSVP.resolve();这里?这两个可以互换吗?

1 个答案:

答案 0 :(得分:3)

首先是

  

我认为Promise.resolve和新的Promise(解决方案)是可以互换的。

不。 Promise.resolve将创建一个已经解决的承诺,而new Promise(resolve)创建既未解决也未被拒绝的承诺。

在最后一个例子中,

return setTimeout(function () {
    return new RSVP.resolve("HI");
}, 3000);

表示您返回setTimeout函数的结果,而不是promise对象。因此,当前then处理程序将返回已解析的promise,其结果为setTimeout。这就是为什么你看到一个奇怪的对象。

在您的特定情况下,您希望在解决承诺之前引入延迟。 Promise.resolve无法实现。您在问题中显示的倒数第二种方法是要走的路。

相关问题