我似乎无法找到这个问题的相关解决方案。
我试图使用foreach循环来调用数据。我已经在承诺中尝试了多种包装方式,但似乎无法在完成循环之前停止此功能。希望有人可能有一些见解。
async function getData(){
temparray [] = { data to iterate over };
await getAgents();
console.log('done');
function getAgents(){
return new Promise(resolve => {
temparray.forEach((deal) => {
pipedrive.Persons.get(deal.agent, function(err, person) {
if (err) throw err;
console.log("trying to get agent " + deal.agent)
console.log(person.name);
});
});
}); // end of promise
};
};
所以我在这里尝试做的是创建一个在所有异步调用完成后解析的promise,但是在此过程完成之前该过程继续进行。因此,在getAgents()函数完成并记录名称之前,“done”会记录到控制台。我怀疑它与回调有关,但我已经尝试将其转换为承诺,我尝试过util.promiseify,我已经看过构建一个promises数组然后使用promise.all但是没有测试了它。
这是你应该如何处理另一个例子
exec = async () => {
let tmp = [1,2,3,4,5,6];
let promises = [];
tmp.forEach(id => {
promises.push(getIdAfterTimeout(id));
});
let value = await Promise.all(promises);
console.log(value);
}
getIdAfterTimeout = (id) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve(id);
}, 2000);
})
}
exec();
async function getData(){
temparray [] = { data to iterate over };
// promises array
let promises = [];
// insert to promises array
temparray.forEach(temp => {
promises.push(getAgents(temp));
})
// this or you can do await
Promise.all(promises)
.then((data) => {
console.log('done');
})
.catch(e => {
console.log('error' );
})
// if you do await .. do like this
const {error, data } = await Promise.all(promises);
console.log(data);
}
function getAgents(id){
return new Promise((resolve, reject) => {
pipedrive.Persons.get(deal.agent, function(err, person){
if (err)
return resolve({error: err, data: null});
return resolve({error : null, data: person});
});
}); // end of promise
}
您可以将具有回调样式的函数转换为承诺。
我的例子是你的情况:
async function getData() {
temparray[] = {data to iterate over};
let persons = await getAgents(temparray);
console.log(persons);
console.log('done');
};
async function getAgents(temparray) {
await Promise.all(
temparray.map((deal) => {
return new Promise(resolve => {
pipedrive.Persons.get(deal.agent, function(err, person) {
if (err) throw err;
console.log("trying to get agent " + deal.agent)
console.log(person.name);
resolve(person);
});
})
})
);
};
你可以使用Promise.all
或旧学校循环(fori
),我想你需要阅读更多关于Promise async / await的信息。
我昨天甚至陷入了类似的问题。我应用以下逻辑来解决这个问题
const fs = require('fs');
async function getData() {
const array = [1, 2, 3, 4, 5, 6];
// Create a counter that tracks how many async requests are completed
let counter = 0;
await getAgents();
console.log('done');
async function getAgents() {
return new Promise(resolve => {
array.forEach((item, i) => {
//do async stuff here
fs.writeFile(`${i}.file.txt`, `line in file ${i}`, err => {
if (err) throw err;
// Increment the counter in the callback function of async request
// Add check if counter is equal to length of array
if (++counter == array.length) {
// Resolve the promise once the counter is equal to the length of input array
resolve(counter);
}
});
});
});
}
}
getData();