如何正确处理父级异步调用中的一系列异步调用

问题描述 投票:0回答:3

我有一个用例,我想进行一个异步调用(类似于ajax),然后在该调用的成功块中,我想使用由父级生成的ID在一个循环中进行一系列异步调用呼叫。我的要求是:

  1. 我将展示成功吐司的代码放在哪里?当前,我将其放在成功块内的for循环之后,但是它有一个问题,它将在子异步调用完成之前执行,因为for循环不会等待调用,并且会立即执行,并且代码将消失展示成功的烤面包。
  2. [如果子调用中的任何一个失败,则不应再进行任何调用(从效率的角度来看更多),而且在这种情况下,我应该能够删除已创建的父记录,因此如何还要处理吗?预先感谢!

示例代码段:

asyncCallA(inputId)
    .then(output => {
        // inputIdsForChildCalls is the list of inputIds for child async 
        // calls
        inputIdsForChildCalls = [do something with output]
        for (let i = 0; i < inputIdsForChildCalls.length; i++) {
            asyncCallB(inputIdsForChildCalls[i])
                .then(output => {
                    // do something
                })
                .catch(error => {
                    // do something with error
                });
        }
        showSuccessToast("Records created successfully!");
    })
    .catch(error => {
        // do something with error
    });
javascript promise callback asynchronous-javascript
3个回答
0
投票
asyncCallA(inputId)
.then(output => {
    inputIdsForChildCalls = [do something with output]
    Promise.all(inputIdsForChildCalls)
        .then(outputs => {
            // do something
            showSuccessToast("Records created successfully!");
        })
        .catch(error => {
            // do something with error
        });
    }
})
.catch(error => {
    // do something with error
});

0
投票
asyncCallA(inputId)
    .then(output => {
        inputIdsForChildCalls = [do something with output]
        let syncCalls = [];
        for (let i = 0; i < inputIdsForChildCalls.length; i++) {
            syncCalls.push(asyncCallB(inputIdsForChildCalls[i]));
        }
        Promise.all(inputIdsForChildCalls)
           .then(outputs => {
            // do something
            showSuccessToast("Records created successfully!");
           })
        .catch(error => {
            // do something with error
        });
    })
    .catch(error => {
        // do something with error
    });

0
投票

确保异步链接发生的最佳选择是使用array.reduce函数下面是相同的示例代码。

如果您不清楚array.reduce和promise如何工作。我建议您参考这篇文章。

https://developers.google.com/web/fundamentals/primers/promises

下面是示例代码,您可以使用。

asyncCallA(inputId)
    .then(output => {
        // inputIdsForChildCalls is the list of inputIds for child async 
        // calls
        inputIdsForChildCalls = [];

        inputIdsForChildCalls.reduce(function(sequence, Id)
        {
            return sequence.then(function()
          {
             return asyncCallB(Id);
          }).then(function(asyncCallResult)
                {
              //do something
        });
        }, Promise.resolve())

    })
    .then(function()
    {
        showSuccessToast("Records created successfully!");
    })
    .catch(error => {
        // do something with error
    });
© www.soinside.com 2019 - 2024. All rights reserved.