How to run multiple async functions then execute callback

后端 未结 3 805
甜味超标
甜味超标 2020-12-05 10:16

In my NodeJS code I need to make 2 or 3 API calls, and each will return some data. After all API calls are complete I want to collect all the data into a single JSON object

3条回答
  •  伪装坚强ぢ
    2020-12-05 10:25

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

    Promise.all is now included with ES6 so you don't need any 3rd party libraries at all.

    "Promise.all waits for all fulfillments (or the first rejection)"

    I've setup a gist to demonstrate Promise.all() with refactoring itterations at: https://gist.github.com/rainabba/21bf3b741c6f9857d741b69ba8ad78b1

    I'm using an IIFE (Immediately Invoked Function Expression). If you're not familiar, you'll want to be for the example below though the gist shows how with using an IIFE. https://en.wikipedia.org/wiki/Immediately-invoked_function_expression

    TL;DR

    ( function( promises ){
        return new Promise( ( resolve, reject ) => {
            Promise.all( promises )
                .then( values => {
                    console.log("resolved all promises")
                    console.dir( values );
                    resolve( values.reduce( (sum,value) => { return sum+value }) ); //Use Array.prototype.reduce() to sum the values in the array
                })
                .catch( err => {
                    console.dir( err );
                    throw err;
                });
    
        });
    })([ 
        new Promise( ( resolve, reject ) => {
            console.log("resolving 1");
            resolve( 1 );
        }),
        new Promise( ( resolve, reject ) => {
            console.log("resolving 2");
            resolve( 2 );
        })
     ]).then( sum => { console.dir( { sum: sum } ) } )
    

提交回复
热议问题