nodejs版本v10.14.2 操作系统win7 sp1 64位
我需要以下四行代码才能按顺序执行
var res2 = await fetchData(url_2, file_path_2);
await console.log('step one.');
var res1 = await fetchData(url_1, file_path_1);
await console.log('step two.');
但是,其执行的实际顺序是
第一步。 第二步。 ........ ........
我们如何实现这四行代码的同步执行?
var https = require('https');
var fs = require('fs');
var request = require('request');
var async = require("async");
(async() => {
var url_1 = 'https://aaa.bbb.ccc.com';
var url_2 = 'https://library.harvard.edu/';
var file_path_1 = fs.createWriteStream('./intelcenter/aaa.bbb.ccc.txt');
var file_path_2 = fs.createWriteStream('./intelcenter/harvard.txt');
var res2 = await fetchData(url_2, file_path_2);
await console.log('step one.');
var res1 = await fetchData(url_1, file_path_1);
await console.log('step two.');
})();
async function fetchData(url,locpath) {
return new Promise(function (resolve) {
async.retry(request(url).pipe(locpath), function(err, result) {
resolve(result);
});
});
}
答案 0 :(得分:1)
同步代码
我为请求模块添加了回调函数,并通过下一个方法传递结果。
默认情况下,async.retry将重试5次。
var fs = require("fs");
var request = require("request");
var async = require("async");
(async () => {
var url_1 = "https://google.com";
var url_2 = "https://library.harvard.edu/";
var file_path_1 = fs.createWriteStream("./intelcenter/aaa.bbb.ccc.txt");
var file_path_2 = fs.createWriteStream("./intelcenter/harvard.txt");
var res2 = await fetchData(url_2, file_path_2);
console.log("step one." + res2);
var res1 = await fetchData(url_1, file_path_1);
console.log("step two." + res1);
})();
function fetchData(url, locpath) {
console.log("inside fetchData");
return new Promise(function(resolve, reject) {
async.retry(
function(next) {
request(url, function(err, result) {
if (err) {
console.log(err);
}
console.log("inside request");
next(result);
}).pipe(locpath);
},
function(result) {
resolve(result);
}
);
});
}
进一步了解async。
没有async.retry的同步代码
var fs = require("fs");
var request = require("request");
(async () => {
var url_1 = "https://google.com";
var url_2 = "https://library.harvard.edu/";
var file_path_1 = fs.createWriteStream("./intelcenter/aaa.bbb.ccc.txt");
var file_path_2 = fs.createWriteStream("./intelcenter/harvard.txt");
var res2 = await fetchData(url_2, file_path_2);
console.log("step one.");
var res1 = await fetchData(url_1, file_path_1);
console.log("step two.");
})();
function fetchData(url, locpath) {
console.log("inside fetchData");
return new Promise(function(resolve, reject) {
request(url, function(err, result) {
if (err) {
console.log(err);
}
console.log("got result");
result=JSON.stringify(result);
locpath.write(result);
resolve(result);
});
});
}