javascript - Promise 的返回值不稳定

标签 javascript promise async-await fs

我仍在尝试理解 JS 中的同步性。以下脚本可以记录不同的值。如何确保它记录稳定的值?感谢任何帮助。

// variable "all" is the array which holds the file path as string
all.forEach(async(f) => {
    promise = new Promise((resolve, reject) => {
        fs.readFile(f, 'utf8', function (err, content) {
            if (!err) {
                scenario += (content.match(/Scenario(\s?)\(\'/g) || []).length;
                uc += (content.match(/\/\/(\s?)UC-(.)+/g) || []).length;
                resolve([scenario, uc]);
            } else {
                reject('Error!');
            }
        });
    });
    await promise;
});

promise.then(([scenario, uc]) => {
    console.log('Total Scenarios: ' + scenario);
    console.log('Total UCs: ' + uc);
});

编辑:以下代码对我来说可以正常工作

引用@Yftach 和@Manjeet Thakur 的回复。

这段代码对我来说工作正常;

let promises = all.map(f => {
        return new Promise((resolve, reject) => {
            fs.readFile(f, 'utf8', function (err, content) {
                if (!err) {
                    scenario += (content.match(/Scenario(\s?)\(\'/g) || []).length;
                    uc += (content.match(/\/\/(\s?)UC-(.)+/g) || []).length;
                    resolve([scenario, uc]);
                } else {
                    reject('Error!');
                }
            });
        });
    });

    Promise.all(promises).then((result) => {
        let max = result.reduce((acc, curr) => {
            return [Math.max(acc[0],curr[0]), Math.max(acc[1],curr[1])];
        });

        console.log('Total Scenarios: ' + max[0]);
        console.log('Total UCs: ' + max[1]);
    });
});

最佳答案

你的代码将无法工作,因为你只等待一个 promise , 你应该做的是使用 Promise.all(arrayOfPromises),该方法将返回一个新的 Promise,该新的 Promise 仅在数组中的所有 Promise 完成后运行。

let allPromises = all.map((f) => {
    promise = new Promise((resolve, reject) => {
        fs.readFile(f, 'utf8', function (err, content) {
            if (!err) {
                scenario += (content.match(/Scenario(\s?)\(\'/g) || []).length;
                uc += (content.match(/\/\/(\s?)UC-(.)+/g) || []).length;
                resolve({scenario:scenario, uc:uc});
            } else {
                reject('Error!');
            }
        });
    });
    return promise;
});

Promise.all(allPromises).then((values) => {
    // Sum all the scenarios and UCS, becase the values is an array of objects representing answers from each promise, we must sum them ourselves
    console.log('Total Scenarios: ' + values.reduce((accumulated, current) => accumulated + current.scenario, 0);
    console.log('Total UCs: ' + values.reduce((accumulated, current) => accumulated + current.uc, 0););
});

注意:如果内部 promise 之一拒绝,“所有” promise 将被拒绝,因此,如果您想忽略这种情况并对其余 promise 求和,则需要使用“空”来解决 promise "值,然后在最后的 then 中进行求和。

关于javascript - Promise 的返回值不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53593200/

相关文章:

javascript - 如何使图像从左侧 0,0 位置向右滑动到右侧末端?

c# - Async-Await 与 Task<T>.Result on WP8

javascript - jQuery计算输入的剩余字符长度

javascript - 使用 Redux 获取数据时如何避免竞争条件?

javascript - 如何使用 jQuery 防止 ajax 请求跟随重定向

javascript - VueJS 中的 promise 问题

javascript - Promise.then() 在 Promise 解决之前执行

javascript - 在循环中为列表对象添加属性并返回该对象,但未应用

c# - 您是否必须将 Task.Run 放入方法中以使其异步?

c# - await 语句后的代码不运行