【发布时间】:2019-07-08 10:16:10
【问题描述】:
我尝试使用 jQuery 处理 JS 承诺。 我有一连串这样的承诺:
function myPromisesChain(data)
{
return $.when(data)
.then(firstStep)
.then(secondptStep)
.then(thirdStep)
// ...n Step
.then(finalStep)
.always(function(data){
console.log('FINISHED: ' + JSON.stringify(data));
});
}
这很好,但是如果我需要在循环中执行一个步骤,该怎么办?伤心,但到目前为止我找不到正确的语法......我期待这样的事情(大约):
function myPromisesChain(data)
{
return $.when(data)
.then(firstStep)
.then(secondptStep)
.then(function(data){
var counter = 0;
var limit = 3;
while(counter<limit){
thirdStep(data.transaction[counter]);
counter++;
}
return data;
})
// ...n Step
.then(finalStep)
.always(function(data){
console.log('FINISHED: ' + JSON.stringify(data));
});
}
问题是循环中的函数本身就是一个承诺。
【问题讨论】:
-
你可能想看看
async/await -
您的问题需要在这里澄清另一点,您要循环执行thirdStep。但是你想串联还是并联执行?如果你想串行执行,我的解决方案可以工作,如果你想并行执行,你需要使用@effective-robot提供的解决方案
标签: javascript jquery promise