How to chain promises in for loop in vanilla javascript

后端 未结 1 414
小蘑菇
小蘑菇 2021-01-25 11:40

If I am doing an async call like the following, how can chain them with promises, so i can do stuff in order? In this example, what ends up happening is that arr wi

相关标签:
1条回答
  • 2021-01-25 12:17

    Assuming your ajax calls can actually be run in parallel and you just want the results in order, then you can promisify the ajax function and use Promise.all() to get all the results in order:

    // promisify the ajax call
    function fbAPIPromise(path, args) {
        return new Promise(function(resolve, reject) {
            FB.api(path, args, function(results) {
                if (!result) return resolve(null);
                if (result.error) return reject(result.error);
                resolve(result);
            });
        });
    }
    
    var promises = [];
    for (var x = 0; x < 10; x++) {
         promises.push(fbAPIPromise('/' + fbArrOfAlbumNames[x] + '/photos/', {fields: 'picture,album'});
    }
    Promise.all(promises).then(function(results) {
         // results is an array of results in original order
    }).catch(function(err) {
         // an error occurred
    });
    
    0 讨论(0)
提交回复
热议问题