【问题标题】:Unstable return value from promisePromise 的返回值不稳定
【发布时间】:2019-05-04 17:08:48
【问题描述】:

我仍在尝试理解 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]);
    });
});

【问题讨论】:

  • scenariouc 在哪里声明和初始化?
  • 你会使用.mapPromise.all,目前你正在等待一个promise - 你想要做的是等待所有promise。另外 - 考虑util.promisify

标签: javascript promise async-await fs


【解决方案1】:

您的代码将不起作用,因为您只等待一个承诺, 你应该做的是使用 Promise.all(arrayOfPromises),这个方法将返回一个新的 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););
});

注意:如果内部承诺之一被拒绝,则“全部”承诺将被拒绝,因此如果您想忽略这种情况并将其余承诺相加,则需要使用“空”来解决承诺" 值,然后在最后的求和中处理它。

【讨论】:

    【解决方案2】:
    var 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(([scenario, uc]) => {
        console.log('Total Scenarios: ' + scenario);
        console.log('Total UCs: ' + uc);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 2021-04-03
      • 2019-06-30
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多