代码 节点 而其是 递归 方法,我的最终目标是等待进程完成,然后开始另一个进程。因为它将写到 数据库.
router.post('/contactImport', function (req, res) {
var ContactList = req.body.contacts;
var pageSize = 3;
var offset = 0;
ImportingContactTest(contactList, pageSize, offset, function (callbackTestCall) {
console.log("ImportingContactTest_final: ", callbackTestCall);
});
res.send("Ok");
});
递归函数。
function ImportingContactTest(contactList, pageSize, offset, callbackImportingContactTest) {
const fragment = GetContactFragment(contactList, pageSize, offset);
console.log("fragmentData_length: ", fragment.data.length);
if (fragment.nextPage) {
offset = fragment.nextPage;
console.log("offset: ", offset);
ImportingContactTest(contactList, pageSize, offset, function (callbackImportingContactTest_1) {
console.log("Test Processes");
callbackImportingContactTest("All Done");
});
} else {
callbackImportingContactTest("All Done Else");
}
};
递归函数: 获取上传的批次。
const GetContactFragment = (contactList, pageSize, offset = 0) => {
return {
data: contactList.slice(offset, offset + pageSize),
nextPage: offset +
pageSize < contactList.length ? offset + pageSize : undefined
}
};
我现在得到的结果:
ContactList: 10
pageSize: 3
fragmentData_length: 3
offset: 3
fragmentData_length: 3
offset: 6
fragmentData_length: 3
offset: 9
fragmentData_length: 1
Test Processes
Test Processes
Test Processes
ImportingContactTest_final: All Done
我想要的结果。
ContactList: 10
pageSize: 3
fragmentData_length: 3
offset: 3
Test Processes
fragmentData_length: 3
offset: 6
Test Processes
fragmentData_length: 3
offset: 9
Test Processes
fragmentData_length: 1
ImportingContactTest_final: All Done
从我的角度来看,你的代码设计得太过火了。异步回调,a 同步功能 就能完成工作。
const GetContactFragment = (contactList, pageSize, offset = 0) => {
return {
data: contactList.slice(offset, offset + pageSize),
nextPage: offset +
pageSize < contactList.length ? offset + pageSize : undefined
}
};
function ImportingContactTest(contactList, pageSize, offset,callbackImportingContactTest) {
var fragment = GetContactFragment(contactList, pageSize, offset);
console.log("fragmentData_length: ", fragment.data.length);
if (fragment.nextPage !== undefined) {
offset = fragment.nextPage;
console.log("offset: ", offset);
console.log("Test Processes");
ImportingContactTest(contactList, pageSize, offset);
fragment = GetContactFragment(contactList, pageSize, offset);
}else {
return
}
};
var contactList = [1,2,3,4,5,6,7,8,9,10];
var pageSize = 3;
var offset = 0;
ImportingContactTest(contactList, pageSize, offset)
console.log("ImportingContactTest_final");
输出。
> "fragmentData_length: " 3
> "offset: " 3
> "Test Processes"
> "fragmentData_length: " 3
> "offset: " 6
> "Test Processes"
> "fragmentData_length: " 3
> "offset: " 9
> "Test Processes"
> "fragmentData_length: " 1
> "ImportingContactTest_final"