XMLHTTPRequest in forEach 循环不起作用



嗨,我正在编写一个短节点.js应用程序,每次迭代数组时都会向API发送XMLHTTPRequest。问题是由于异步性质,它在返回请求之前继续 foreach 循环。我可能忽略了一些大事,但我花了今天下午的大部分时间试图为此绞尽脑汁。我尝试使用等待无济于事,任何解决方案将不胜感激。

提前谢谢。

节点 JS 应用

const mongoose = require("mongoose");
const fs = require("fs");
const ajax = require("./modules/ajax.js");
// Bring in Models
let Dictionary = require("./models/dictionary.js");

//=============================
//     MongoDB connection
//=============================
// Opens connection to database "test"
mongoose.connect("mongodb://localhost/bookCompanion");
let db = mongoose.connection;
// If database test encounters an error, output error to console.
db.on("error", (err)=>{
console.console.error("Database connection failed.");
});
// Check for connection to the database once.
db.once("open", ()=>{
console.info("Connected to MongoDB database...");
fs.readFile("./words.json", "utf8", (err, data)=>{
if(err){
console.log(err);
} else {
data = JSON.parse(data);
data.forEach((word, index)=>{
let search = ajax.get(`LINK TO API?=${word}`);
search.then((response)=>{
let newWord = new Dictionary ({
Word: response.word,
phonetic: response.phonetic,
meaning: response.meaning
}).save();
console.log(response);
}).catch((err)=>{
console.log(err);
});
});
}
});

});

XMLHTTPRequest Module

// Get Request module utilising promises
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const get = (url)=>{
// This function will return a promise, promises use resolve and reject. The resolve is accessed through .then and the reject through the .catch
return new Promise((resolve, reject)=>{
// Create new XMLhttp (AJAX) Request
let xhr = new XMLHttpRequest();
// Sets up the request, setting it to a GET request, pointing to the website and setting it to asynchronous
xhr.open("GET", url , true);
//sends the request
xhr.send();
xhr.onload = ()=>{
if (xhr.status == 200){
// When loaded pass the response over to the .then method
resolve(JSON.parse(xhr.responseText));
} else {
// if error pass the status code to the .catch method for error handling
reject(xhr.statusText);
}
};
xhr.onerror = ()=>{
// if error pass the status code to the .catch method for error handling
reject(xhr.statusText && xhr.status);
};
});
};
module.exports.get = get;

你应该使用 promise.all 来等待所有 promise 完成。Promise.all 将一系列承诺作为输入,并等待所有承诺得到解决。它拒绝了 如果你使用 promise.all,你的代码将是这样的。

const mongoose = require("mongoose");
const fs = require("fs");
const ajax = require("./modules/ajax.js");
// Bring in Models
let Dictionary = require("./models/dictionary.js");

//=============================
//     MongoDB connection
//=============================
// Opens connection to database "test"
mongoose.connect("mongodb://localhost/bookCompanion");
let db = mongoose.connection;
// If database test encounters an error, output error to console.
db.on("error", (err) => {
console.console.error("Database connection failed.");
});
// Check for connection to the database once.
db.once("open", () => {
console.info("Connected to MongoDB database...");
fs.readFile("./words.json", "utf8", (err, data) => {
if (err) {
console.log(err);
} else {
data = JSON.parse(data);
var promiseArr = []
Promise.all(promiseArr.push(
new Promise((resolve, reject) => {
let search = ajax.get(`LINK TO API?=${word}`);
search.then((response) => {
let newWord = new Dictionary({
Word: response.word,
phonetic: response.phonetic,
meaning: response.meaning
}).save();
console.log(response);
resolve();
}).catch((err) => {
console.log(err);
reject();
});
})
)).then((response) => {
//whatever you want to do after completion of all the requests
})
}
});

});

在使用较小的数组时,我的代码似乎工作正常,我遇到的真正问题是处理forEach循环和内存的阻塞性质。我需要循环访问的数组由超过 400,000+ 个单词组成,并且在 forEach 循环完成并释放调用堆栈以供 httprequests 解析之前,应用程序内存不足。

有关如何创建不阻塞调用堆栈的同步 forEach 循环的任何信息将不胜感激。

最新更新