首页 文章

顺序Firebase Cloud 功能承诺

提问于
浏览
0

我仍然没有得到如何使 Cloud 功能顺序工作 . 这是我的代码:

export const Run = functions.database.ref("PATH").onUpdate((snap, 
context) =>
{
const Collection = [];
ref.child('PATH2').once('value', function(lambda) 
{
    lambda.forEach((snap) => 
    {
        if (snap.val().state) 
        {
            Collection.push(snap.key);
        }
        return false; //since I use typescript I must return a boolean with foreach loop
    });
}).then(() => 
{
for (let i = 0; i < Collection.length; i++) 
{
    const arg = Collection[i];

        if(Verify(arg))
        {
            break;
        }

        Function_A(arg)
        .then(() => {
            return Function_B(arg)
        })
        .then(() => {
            return Function_C(arg);
        })
        .then(() => {
            return Function_D(arg);
        })
        .then(() => {
            return Function_E(arg)
        })
        .then(() => {
            return Function_F(arg)
        })
        .then(() => {
            return Function_G(arg)
        })
}
})
});

问题是功能C在功能B完成之前启动 . 我怎么能让它顺序工作?在进入下一个功能之前,我真的需要完全实现功能B.

1 回答

  • 1

    让许多promises(“promise-returns asynchronous functions”)按顺序运行的规范方法是链接它们 .

    Promise.resolve(init)
        .then(result => function1(result))    // result will be init
        .then(result => function2(result))    // result will be the result of function1
        .then(result => function3(result));   // result will be the result of function2
                                              // overall result will be that of function 3
    
    // more succinctly, if each function takes the previous result
    Promise.resolve(init).then(function1).then(function2).then(function3);
    

    这种模式可以一般表示,即使用可变数量的函数,使用数组和 .reduce() 调用:

    var funcs = [function1, function2, function3, functionN];
    var chain = funcs.reduce((result, nextFunc) => nextFunc(result), Promise.resolve(init));
    

    这里 chain 是一个单一的承诺(链中的最后一个) . 它将在链解决时解决 .

    现在,假设我们有函数A到G,并假设 lambda 是一个值数组:

    const funcSequence = [Function_A, Function_B, Function_C, Function_D, Function_E, Function_F, Function_G];
    
    const chains = lambda
        .filter(snap => snap.val().state && Verify(snap.key))
        .map(snap => funcSequence.reduce((result, func) => func(snap.key), Promise.resolve(/* init */)));
    

    chains 将是一个承诺链数组(精确地说是每个链的最后承诺数组) . 所有链都将并行运行,但每个链都将按顺序运行 . 我们现在需要做的就是等待所有人解决 .

    Promise.all(chains).then(results => console.log(results));
    

    Todo:添加错误处理 .

    以上也可以使用循环和 async / await 来完成 . 您可以转换代码,看看您更喜欢哪种方法 .

相关问题