我的代码如下:
function get_btc(address) {
address_transaction(address, user_id, coin_key, deposite_txn_fee, function (callback) {
for (var j = 0; j < callback.response.data.txs.length; j++) {
let user_id = callback.user_id;
//some code//
}
});
}
get_label_info(function (err, data) {
var promise = [];
for (var i = 0; i < data.length; i++) {
let address = data[i].address;
var test_function = function (done) {
deposite_model.get_coin_info(function (err, data1) {
var coin_name = data1[0].coin_code;
const return_functions = get_switch(coin_name);
if (return_functions) {
obj[return_functions](address);
}
done(err, data1);
});
};
promise.push(test_function);
}
sample();
});
function sample() {
console.log('all functions has been completed');
}
在上面提到的代码的帮助下,我希望在完成所有函数后执行all_completed循环。 在初始启动时,get_label_info函数被执行,然后控制器继续执行get_btc函数。
请帮助我在完成所有功能运行后如何运行all_completed函数。
答案 0 :(得分:1)
试试这个,
在for循环外定义test_function,这不是在循环内声明的好方法。
var test_function = function (address) {
return new Promise((resolve, reject) => {
deposite_model.get_coin_info(function (err, data1) {
if (err)
return reject(err);
var coin_name = data1[0].coin_code;
const return_functions = get_switch(coin_name);
if (return_functions) {
obj[return_functions](address);
}
return resolve(data1);
})
})
}
get_label_info(function (err, data) {
var promises = [];
for (var i = 0; i < data.length; i++) {
promises.push(test_function(address));
}
Promise.all(promises).then((data) => {
sample();
})
});
function sample() {
console.log('all functions has been completed');
}