从q.js承诺链中的任何承诺获取和设置值

时间:2014-08-12 17:50:29

标签: javascript promise q

我必须处理函数调用返回到半外部库的长promise链和子链。我遇到了必须从另一个子链的子链访问价值的情况(下面的简化示例)。

我希望获得/查询某些之前的承诺已设置的值,而无需通过链中的每个承诺手动传递该值。如果这对任何事都有帮助,那么这个值就不必是一个返回值。

这样做的最佳做法是什么?请注意,由于我们生活在异步世界中,同一链的多个实例可能同时处理...

function doNothing {
   return true;
}

function setValue {
   // somehow set <some> property to '1234'
}

function accessValue {
   // somehow read from <some> property '1234'
}

Q( true ).then( doNothing )
   .then( doNothing )
   .then( doNothing )
   .then( function() {
       return Q( true ).then( doNothing ).then( setValue ).then( doNothing );
   } )
   .then( function() {
       return Q( true ).then( doNothing ).then( accessValue ).then( doNothing );
   } )
   .done();

1 个答案:

答案 0 :(得分:0)

结束在Q之上编写我自己的实现,可在此处获取:https://github.com/franksrevenge/q/tree/v1-data-dispatch

工作原理如下:

function doNothing {
    return true;
}

Q( true ).then( doNothing )
    .then( doNothing )
    .then( doNothing )
    .then( function() {
        return Q( true ).then( doNothing )
        .local(function(localData) {
            localData.myValue = 1234;
        }).then( doNothing );
   } )
   .then( function() {
        return Q( true ).then( doNothing ).local(function(localData) {
            console.log(localData.myValue);
        }).then( doNothing );
   } )
   .done();