如何通过promises使这段代码异步?

时间:2017-08-15 07:11:26

标签: javascript node.js ecmascript-6 es6-promise

任何胶水。 请不要举例说明SETTIMEOUT。

我的主管说如果then()没有返回任何新的promise,那么就没有必要使用more then语句。我无法完全理解它,我看过探索ES6但是没有很好的例子我的情况。

let readData = new Promise(function (resolve, reject) {
    fs.readFile('/home/geek/Desktop/activity-logs.csv', 'utf8', (err, data) => {
        if (err)
            reject();
        resolve(data);

    });

});

readData
    .then((data) => {
        bankLogs = splitString(data, ';')
    })
    .then(() => {
        for (let index = 2; index < bankLogs.length; index += 5) {
            objectOfUsers[bankLogs[index]] = {}
            temporarySymbols.push(bankLogs[index].concat(bankLogs[index + 1]));
        }
        Object.keys(objectOfUsers).forEach(function (element) {
            objectKeys.push(element)
        });
        for (let index = 0; index < objectKeys.length; index++)
            createObject(index);
        console.log(objectOfUsers)
    })
    .catch((err) => console.log('Error happened : ' + err));

1 个答案:

答案 0 :(得分:1)

在您的代码段中,您实现了 Promise chain ,其中解析一个承诺初始化并返回新承诺。

类似的东西:

let readData = new Promise(/* ... */);

readData.then((data) => {
        let promise2 = new Promise(/* ... */);
        return promise2;
    }).then(() => {
        // ...
    })
    .catch((err) => console.log('Error happened : ' + err));

然而,在解析readData之后,你只写了简单的逻辑而且没有新的承诺:bankLogs = splitString(data, ';')

所以它应该是:

let readData = new Promise(function (resolve, reject) {
    fs.readFile('/home/geek/Desktop/activity-logs.csv', 'utf8', (err, data) => {
        if (err)
            reject();
        resolve(data);    
    });    
});

readData.then((data) => {
    var bankLogs = splitString(data, ';')

    for (let index = 2; index < bankLogs.length; index += 5) {
        objectOfUsers[bankLogs[index]] = {}
        temporarySymbols.push(bankLogs[index].concat(bankLogs[index + 1]));
    }
    Object.keys(objectOfUsers).forEach(function (element) {
        objectKeys.push(element)
    });
    for (let index = 0; index < objectKeys.length; index++)
        createObject(index);
    console.log(objectOfUsers)
})
.catch((err) => console.log('Error happened : ' + err));

如果您仅在Promise中使用bankLogs,请将其设为私有。

我们主要使用

承诺链方法来获得良好的代码可读性,并为所有承诺处理一个错误回调。

修改

您可以使用一些包装器对象或项目列表(示例)来通过Promise链传递值:

'use strict';

var fs = require('fs');

let readData = new Promise(function (resolve, reject) {
    fs.readFile('/Users/maxim/Appsflyer/projects/ZEVEL/file1.txt', 'utf8', (err, data) => {
        if (err)
            reject();

        var obj = {
            data: data,
            bankLogs: {} // in 1st Promise initialize bankLogs
        };    
        resolve(obj);    
    });    
});

// 2nd dummy Promise 
let newReadData = new Promise(function (resolve, reject) {
    fs.readFile('/Users/maxim/Appsflyer/projects/ZEVEL/file2.txt', 'utf8', (err, data) => {
        if (err)
            reject();
        resolve(data);

    });

});

readData.then((obj1) => {   

    obj1.bankLogs.value = "someValue";

    return newReadData.then(function(data2){       
        obj1.data2 = data2;
        return obj1;
    });
}).then((dataTotal) => {   
    console.log(dataTotal);

})
.catch((err) => console.log('Error happened : ' + err));