Best es6 way to get name based results with Promise.all

前端 未结 5 516
陌清茗
陌清茗 2020-12-09 16:30

By default the Promise.All([]) function returns a number based index array that contains the results of each promise.

var promises = [];
promises.push(myFunc         


        
5条回答
  •  星月不相逢
    2020-12-09 16:49

    A great solution for this is to use async await. Not exactly ES6 like you asked, but ES8! But since Babel supports it fully, here we go:

    You can avoid using only the array index by using async/await as follows.

    This async function allows you to literally halt your code inside of it by allowing you to use the await keyword inside of the function, placing it before a promise. As as an async function encounters await on a promise that hasn't yet been resolved, the function immediately returns a pending promise. This returned promise resolves as soon as the function actually finishes later on. The function will only resume when the previously awaited promise is resolved, during which it will resolve the entire await Promise statement to the return value of that Promise, allowing you to put it inside of a variable. This effectively allows you to halt your code without blocking the thread. It's a great way to handle asynchronous stuff in JavaScript in general, because it makes your code more chronological and therefore easier to reason about:

    async function resolvePromiseObject(promiseObject) {
        await Promise.all(Object.values(promiseObject));
    
        const ret = {};
    
        for ([key, value] of Object.entries(promiseObject)) {
            // All these resolve instantly due to the previous await
            ret[key] = await value;
        };
    
        return ret;
    }
    

    As with anything above ES5: Please make sure that Babel is configured correctly so that users on older browsers can run your code without issue. You can make async await work flawlessly on even IE11, as long as your babel configuration is right.

提交回复
热议问题