Sequential Firebase云功能承诺



我仍然不知道如何使云函数按顺序工作。这是我的代码:

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完全完成。

让多个promise("promise返回异步函数"(按顺序运行的规范方法是将它们链接起来。

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是单个promise(链中的最后一个promise(。链解决后,它就会解决。

现在,假设我们有函数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来完成。您可以转换代码,看看您更喜欢哪种方法。

最新更新