简体   繁体   English

在 javascript 中使用 Promises 运行代码时出现问题

[英]Problem in running code with Promises in javascript

The program description节目说明

Create 3 functions:
FuncA – will receive a string and returns it’s length
FuncB – will receive an array of strings and returns their total lengths (using
funcA) after 2 seconds.
FuncC - will receive an array of arrays of strings and returns their total lengths
(using FuncB)

My solution is我的解决方案是

    function funcA(s)
    {
        return s.length
    }

    function funcB(arr)
    {
        return new Promise(resolve =>
            {
                setTimeout(() =>
                {
                    let total = 0;
                    arr.forEach(element => {
                        total += funcA(element)
                    });
                    resolve(total)
                },2000)
            })
    }

    function funcC(arr)
    {      
            return new Promise(resolve =>
                {
                    let isFirst = true
                    //a <=> total
                    let total = arr.reduce(async (a,b) =>
                    {
                        if(isFirst) {
                           isFirst = false
                           return (await funcB(a) + await funcB(b))
                        }
                        else {//a <=> total
                            return (a + await funcB(b))
                        }
                    })
                    resolve(total)
                }) 
    }

The running is:运行是:
funcC([["aa","bbb","tyui"],["ccc"],["dfghj","aedtfr"]]).then(x => console.log(x)) funcC([["aa","bbb","tyui"],["ccc"],["dfghj","aedtfr"]]).then(x => console.log(x))

The result is: [object Promise]11结果是: [object Promise]11

What is the problem?问题是什么?

This is really convoluted.这真是令人费解。

  • Don't put business logic in the setTimeout callback.不要将业务逻辑放在setTimeout回调中。 Only resolve the promise, then do the work in a promise then callback or after an await .仅解决 promise,然后在 promise 中执行工作, then回调或await之后。
  • Always pass an initial value to reduce , This will make it work with empty arrays, and it will obviate the need for that really weird isFirst logic.始终将初始值传递给reduce ,这将使其适用于空数组,并且将消除对非常奇怪的isFirst逻辑的需要。
  • total already is a promise. total已经是 promise。 Don't unnecessarily wrap it in a new Promise !不要不必要地将其包装在new Promise

These suggestions will lead to这些建议将导致

function funcA(s) { return s.length }

function funcB(arr) {
    return new Promise(resolve => {
        setTimeout(resolve, 2000);
    }).then(() => {
        let total = 0;
        arr.forEach(element => {
            total += funcA(element)
        });
        return total;
    });
}

function funcC(arr) {      
    return arr.reduce(async (a,b) => {
        return await a + await funcB(b)
    }, Promise.resolve(0))
}

However, reduce is not really suited for asynchronous work .然而, reduce并不真正适合异步工作 You should rather use the looping approach in funcC , and use reduce in funcB where it fits much better:您应该在funcB funcC使用reduce ,它更适合:

async function funcB(arr) {
    await new Promise(resolve => {
        setTimeout(resolve, 2000);
    });
    return arr.reduce((total, element) => total + funcA(element), 0);
}

async function funcC(arr) {
    let total = 0;
    for (const b of arr) {
        total += funcB(b);
    }
    return total;
}

[fixed the answer] [固定答案]

you shall do await a instead of a everywhere你应该await aa到处

function funcC(arr)
{      
    return new Promise(resolve =>
        {
            let isFirst = true
            //a <=> total
            let total = arr.reduce(async (a,b) =>
            {
                if(isFirst) {
                    isFirst = false
                    return (await funcB(await a) + await funcB(b))
                }
                else {//a <=> total
                    return (await a + await funcB(b))
                }
            })
            resolve(total)
        }) 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM