Article From:

forLoop requests the data interface, and for loops out different values as the parameters of the request interface. How do you deal with this? Otherwise, the interface has not been completed, and the for loop has been executed.

Answer 0:

Use promise asynchronously

Answer 1:

Method one: let i=0
Method two:

  for(var i=0;i<bb.length;i++){
     (function (arg) {

1.The simple point is solved by using ES6’s let.
2.Closures are used if ES6 is not supported.

Answer 2:

As for the understanding of asynchronous processing, you can refer to the JavaScript asynchronous call from a small topic step by step.

// If you use node, you can use util.promisify to encapsulate node callback style calls./ / or write one for yourselfFunction updateTaskLastMile (... Args) {Return new Promise ((resolve, reject) => {TaskMainRepo.updatetasklastmile (... Args, (ER)R, data) => {If (ERR) {Reject (ERR);} else {Resolve (data);}});});}Async function main () {Const BB = [];Const promises = (B => updateTaskLastMile (b));/ / this AA is what you wantConst AA = awaIt Promise.all (promises);}

But the above main must be successful for every BB call to return, that is to say, for Promise.all, if there is a failure, it must all fail. This can be rewritten (see async from try-catch./await syntax error handling):

async function main() {
    const bb = [];
    // Pay attention to the.Catch added hereConst promises = (B => updateTaskLastMile (b).Catch (ERR => false));/ / this AA is what you wantConst AA = await Promise.all (promises);}

In this way, if there is a call failure, the corresponding element in AA isfalse,Of course, you can also use other easily recognized values, such asnullundefined Or a special value, or even simply encapsulate the return value.

    const promises = bb
        .map(b => updateTaskLastMile(b)
            .then(data => ({ data }), err => ({ err })));

In this way, every element in AA is an Property, eithererr Property…

Answer 3:


Answer 4:

The array is stored first, then each element is a promise, then it is called by promise.all. When then is returned, it is a result array of one to one.

Link of this Article: Request data interface in for loop

Leave a Reply

Your email address will not be published. Required fields are marked *