- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我们如何实现以下代码片段的同步代码。我们要在前一个函数的回调函数中编写代码。这创造了回调 hell (正如他们所说)。如何分别编写男性和女性分别读取记录并且可以同步执行。我们如何保留 console.log(id[0]); 的值在 for 循环中。如果我的方向错误,请纠正我。
var male_arr = []; var female_arr = [];
/************* Fetching record from database with condition gender=0
***************/ user.find({gender: 0}, {_id: 1}, function (err_male, male) {
if (err_male) {
console.log(err_male);
}
male_arr = male; // initializing males array
looplength = male.length;
//
// With CAALBACK function, we have fetched records with condition gender = 1
//
user.find({gender: 1}, {_id: 1}, function (err_female, female) {
if (err_female) {
console.log(err_female);
}
female_arr = female; // initializing females array
// Populate the male array
for (var loop = 0; loop < looplength; loop++) {
var id = male_arr.splice(0, 1);
//#1 /*****here is the spliced element********/
console.log("Outside request api");
console.log(id[0]);
// Get all records of females which are in request table of male at id[0]
request.find({male: id[0]._id}, {female: 1}, function (err, data) {
//#2 /*****This value of male in id[0] is not retained for match ********/
console.log("Inside request api");
console.log(id[0]);
if (err) {
console.log(err);
}
});
}
}); });
最佳答案
虽然 Caio 的答案可能适合您的问题,但我可以建议使用 Promises 吗?
使用Bluebird你可以这样做:
Note: this is an example and it might not be actually functional.
var Promise = require('bluebird');
var getMaleFn() {
return new Promise(function(resolve, reject){
// Make the call to your API.
// Handle errors, if any, return reject(err);
return resolve(males);
});
}
var getFemaleFn() {
return new Promise(function(resolve, reject){
// Make the call to your API.
// Handle errors, if any, return reject(err);
return resolve(females);
});
}
var males = [];
var females = [];
// Fetch all males
getMaleFn()
//Iterate each male and put it in the array
.map(function(male) {
males.push(male);
})
// Fetch all females
.then(function(){
return getFemaleFn()
})
//Iterate each females and put it in the array
.map(function(female) {
females.push(female);
})
.then(function(){
console.log('done!');
});
关于node.js - 如何控制以下代码片段的 Node.js 的异步性质,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37664315/
Eclipse 坚持在我的项目中启用 JSF 方面。我可以很容易地禁用它,但是当我通过 Eclipse 运行 Maven -> Update Project 时,facet(以及关联的 WEB-INF
我在 Linux 下从 eclipse 导出了一个 SWT 项目,并尝试在 Windows 下导入它。到目前为止,一切都工作正常,除了我似乎失去了该项目的“SWT 性质”。使用 SWT gui 运行项
我有以下项目结构: root-gradle (build.gradle) 项目组 1(无构建文件) project1 (build.gradle) project2 (build.gradle) ..
我正在K8s集群上试验Spark2.3。想知道检查点如何工作?它存储在哪里?如果主驱动程序死了,那么现有处理会怎样? 在从卡夫卡消费时,补偿如何保持?我试图在线查找,但找不到这些问题的任何答案。我们的
我有一个 springboot 项目,它被组织为多个模块。我正在使用 Eclipse 2019-06(版本 4.12)和 jdk 1.8 update 131 和 apache maven 3.3.9
我是一名优秀的程序员,十分优秀!