forEach循环内的XMLHTTPRequest不起作用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了forEach循环内的XMLHTTPRequest不起作用相关的知识,希望对你有一定的参考价值。
嗨,我正在编写一个简短的node.js应用程序,每次迭代数组时都会向API发送XMLHTTPRequest。问题是由于异步性质,它会在返回请求之前继续foreach循环。我可能会忽略一些大事,但我已经花了大半个时间试图让我的脑子在这上面。我已经尝试使用等待无济于事,任何解决方案将不胜感激。
提前致谢。
NODE 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模块
// 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.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循环的任何信息。
以上是关于forEach循环内的XMLHTTPRequest不起作用的主要内容,如果未能解决你的问题,请参考以下文章
按钮操作块内的 Foreach 循环抛出“Type() 不能符合视图”
如何在 foreach 循环内的 laravel 刀片文件中运行不同的 SELECT 查询?