同一promise实例是否可以有多个thenable?

时间:2019-08-08 10:27:08

标签: javascript extjs promise

当我对一个promise对象具有多个可实现的功能时,它将起作用吗?在这种情况下,我不想嵌套。我想对同一个Promise对象执行不同的操作。

var a = 0,
t = null,
promiseFun = function () {
    return new Ext.Promise(function (resolve, reject) {
        t = setInterval(function () {
                if (a == 1) {
                    resolve();
                    clearInterval(t);
                } else if (a == 2) {
                    reject();
                    clearInterval(t);
                }
            }, 1000);
    })
};

var promiseObj = promiseFun();
//handler one
promiseObj.then(function () {
    console.log('resolved 1')
}, function () {
    console.log('rejected 1')
}).then(function () {
    console.log('resolved Nest')
}, function () {
    console.log('rejected Nest')
});

//handler two- this is valid ?
promiseObj.then(function () {
    console.log('resolved 2')
}, function () {
    console.log('rejected 2')
});

//OUTPUT:

//resolved 1
//resolved 2
//resolved Nest

还是我需要用Deffered包装。

1 个答案:

答案 0 :(得分:0)

  

当我对一个promise对象具有多个可实现的功能时,它将起作用吗?

是的,那很好。这称为分支而不是链接。

如果您有这个:

let p = somePromiseGeneratingFunction();
p.then(...).then(...);
p.then(...).then(...);

然后,您仅创建了两个独立的独立的Promise链,每个链均在p解析时启动。如果这是您想要的逻辑,那就完全可以了。

您可以保证的一件事是,第一个p.then()处理程序将在第二个p.then()处理程序被调用之前被调用,但是如果任一链中还有其他异步操作,则它们将在第二个之后独立运行并且不再相互协调。它们是独立且独立的承诺链,它们根据自己的异步操作的时间运行。这就是为什么它被称为“分支”。一个链条分成两个链条。

有关该主题的更多讨论,请参见Is there a difference between promise.then.then vs promise.then; promise.then