![](/img/trans.png)
[英]Is it possible to do something *after* something has finished in Javascript?
[英]http requests inside loop of variable size, how to do something only after last request has finished (JavaScript)
我正在使用 request 在可变大小的循环中发出 HTTP 请求。 (我将从文件中读取单词,现在我只有一个数组)。 我在每个循环中添加一个对象(响应),并且只想在最后一个请求完成后返回该对象。 我一直在玩承诺,但我不确定如何链接它们,因为它是可变数量的请求。
const request = require('request');
// eventually this array will be populated by reading a file
var words = ["hello", "there"];
var response = {};
// Loop thruogh input string
for (var i = 0; i < words.length; i += 1) {
// get next word
var curWord = words[i];
// if the current word is not already in the response
if (!(curWord in response)) {
// request info from dictionary
var options = {
url: 'https://api.dictionaryapi.dev/api/v2/entries/en/' + curWord,
json: true
}
request(options, (err, res, body) => {
if (err) { return console.log(err); }
// find part of speech
var partOfSpeech;
try {
partOfSpeech = body[0].meanings[0].partOfSpeech
} catch (err) {
partOfSpeech = "undefined";
}
// add to response
response[curWord] = partOfSpeech;
});
}
}
// do this part only after last request has been completed
console.log(response);
基本上,您需要计算响应,知道当计数器达到零时,您就完成了所有响应。
const request = require('request');
var words = ["hello", "there"];
var response = {};
var count = words.length;
for (var i = 0; i < words.length; i += 1) {
var curWord = words[i];
if (!(curWord in response)) {
var options = {
url: 'https://api.dictionaryapi.dev/api/v2/entries/en/' + curWord,
json: true
}
request(options, (err, res, body) => {
count--
if (err) {
return console.log(err);
}
// find part of speech
var partOfSpeech;
try {
partOfSpeech = body[0].meanings[0].partOfSpeech
} catch (err) {
partOfSpeech = "undefined";
}
// add to response
response[curWord] = partOfSpeech;
if (count == 0) {
// do this part only after last request has been completed
console.log(response);
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.