gpt4 book ai didi

node.js - 如何控制以下代码片段的 Node.js 的异步性质

转载 作者:太空宇宙 更新时间:2023-11-04 03:31:09 25 4
gpt4 key购买 nike

我们如何实现以下代码片段的同步代码。我们要在前一个函数的回调函数中编写代码。这创造了回调 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com