异步操作完成后运行函数



我正在用头撞墙来弄清楚如何将异步写入文件的数据推送到数组中。同步写入数据(并检查该项目是否是列表中的最后一个(需要太多时间,所以我决定让它异步运行。经过一些研究,似乎我可以使用回调

我宁愿不使用外部库来执行此操作,因为我很确定回调或 Promise 应该可以解决问题。谢谢!

//Iterate through list and make HTTP request to get data
dataDocument.map(function(item, index) {
    request(item, function(err, res, html) {
        if (err) throw err;
        renderData(html, item);
    });
});
//Renders data 
function renderData(html, item) {
    ...some calculations here.
    writeData(output, id, function() {
        pushed(output);
    });
};
//Writes the data on file
function writeData(output, id) {
    fs.appendFile('./output.json', output);
//SHOULD I USE A CALLBACK HERE TO PUSH INTO AN ARRAY ONCE IT'S COMPLETE?
};
//NEED HELP HERE: Pushed the data into an array and eliminates last comma.
function pushed(data) {
   var arr = [];
   arr.push(data);
}

有了承诺,它看起来会更干净、更精简。承诺所有相关功能,并使用Promise.all来了解何时收集了所有数据:

// Promisify all the involved callback-based functions:
function promiseRequest(item) {
    return new Promise(function (resolve, reject) {
        request(item, function (err, res, html) {
            if (err) {
                reject(err);
            } else {
                resolve(html);
            }
        })
    })
}
//Renders data 
function promiseRenderData(html, item) {
    //...some calculations here.
    return promiseWriteData(output, id).then(function() {
        return output;
    });
};
//Writes the data on file
function promiseWriteData(output, id) {
    return new Promise(function (resolve, reject) {
        fs.appendFile('./output.json', output, function (err) {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}
//Iterate through list and make HTTP request to get data
Promise.all(dataDocument.map(function(item, index) {
    return promiseRequest(item).then(function(html) {
        return promiseRenderData(html, item);
    };
})).then(function(arr) {
    // Do something with `arr` here
});

最新更新