Promise.resolve和新Promise(resolve)可以互换吗

Are Promise.resolve and new Promise(resolve) interchangeable

本文关键字:Promise resolve 互换 和新      更新时间:2023-09-26

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

考虑一下:

A。

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

B。

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();在这里这两个可以互换吗?

首先是

我认为Promise.resolve和new Promise(决心)是可以互换的。

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


在最后一个例子中,

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

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


在您的特定情况下,您希望在解决承诺之前引入延迟。Promise.resolve不可能。你在问题中展示的倒数第二个方法,就是要走的路。