我四处寻找,但无法理解 promise 。我所理解的是如何定义一个 Promise 并通过使用 .then 使用其结果。
我不明白的是如何创建一个循环来查询数据库中的不同记录 block 。由于要查询的记录数量受到限制,因此需要这样做。
预定义的 Promise api 调用的使用方式如下:
let getRecords = (name) => {
return new Promise((resolve,reject) => {
xyz.api.getRecords(name, 1000, 1000, function(err, result){
// result gets processed here.
resolve(//somevariables here);
});
)};
按照我习惯的方式,我尝试过:
for (let i=1; i<90000; i+=500) {
xyz.api.getRecords('james', i, 500, function(err, result){
// result gets processed here.
});
}
但是我无法访问该信息(可能是我做错了) 还尝试过这样的事情:
function getRecords(name,i){
xyz.api.getRecords(name, i, 500, function(err, result){
// result gets processed here.
});
};
for (let i=1; i<90000; i+=500) {
var someThing = getRecords('james', i);
}
所有教程似乎都只使用一个查询,并处理数据。
如何使用不同的参数多次调用 api 函数、收集数据并在检索到所有内容后对其进行处理? 我唯一能想到的就是,将信息写入文件,这是一个糟糕的想法。
最佳答案
使用async
/await
(async () => {
function getRecords(name,i){
// create new Promise so you can await for it later
return new Promise((resolve, reject) => {
xyz.api.getRecords(name, i, 500, function(err, result){
if(err) {
return reject(err);
}
resolve(result);
});
});
}
for (let i = 1; i < 90000; i += 500) {
// wait for the result in every loop iteration
const someThing = await getRecords('james', i);
}
})();
要处理错误,您需要使用 try/catch
block
try {
const someThing = await getRecords('james', i);
} catch(e) {
// handle somehow
}
仅使用Promise
function getRecords(name, i) {
// create Promise so you can use Promise.all
return new Promise((resolve, reject) => {
xyz.api.getRecords(name, i, 500, function (err, result) {
if (err) {
return reject(err);
}
resolve(result);
});
});
}
const results = [];
for (let i = 1; i < 90000; i += 500) {
// push Promise's to array without waiting for results
results.push(getRecords("james", i));
}
// wait for all pending Promise's
Promise.all(results).then((results) => {
console.log(results);
});
let count = 0;
function getRecords(name, i) {
return new Promise((resolve, reject) => {
setTimeout(() => {
// example results
resolve((new Array(10)).fill(0).map(() => ++count));
}, 100);
});
}
const results = [];
for (let i = 1; i < 9000; i += 500) {
results.push(getRecords("james", i));
}
Promise.all(results).then((results) => {
console.log("Results:", results);
console.log("Combined results:",[].concat(...results));
});
要处理错误,您需要使用.catch()
block
Promise.all(results).then((results) => { ... }).catch((error) => {
// handle somehow
});
关于javascript - 谁可以向 PHP 程序员解释循环中的 NodeJS Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335323/