我在Stackoverflow上看到了很多答案,建议人们使用Promise.all
处理多个异步调用。我确实认为Promise.all()在进行调用以完成类似工作时会有所帮助,但是这种方法存在一些问题:
有其他方法吗?
例如,在React(使用钩子)中,我们可以执行以下操作:
useEffect(() => {
setValue1(await fetch(url1));
});
useEffect(() => {
setValue2(await fetch(url2));
});
但是,这对我来说并不正确……不过,这也许是“正确的”。
无论如何,我之所以发表这篇文章,是因为我真的很感谢有关如何处理处理不同逻辑的异步调用的一些很好的指示。
谢谢。
答案 0 :(得分:-1)
您需要在此处添加异步
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
double avg(const vector<double>& v){
int sum = 0;
for (int i = 0; i < v.size(); i++)
sum+= v.at(i);
return (1.0 * sum / v.size());
}
double max(const vector<double>& v) {
int maxelt = v.at(0);
for (int i = 1; i < v.size(); ++i) {
if (v.at(i) < maxelt)
maxelt = v.at(i);
}
return (maxelt);
}
void selection_sort(vector<double>&a, vector<double>& b) {
int max;
for(int i = 0; i < a.size()-1; i++) {
max = i;
for (int j = i + 1; j < a.size(); j++)
if((a.at(j) > a.at(max)) || ((a.at(j) == a.at(max)) &&
(b.at(j) < b.at(max)))
)
max = j;
swap(a.at(i), a.at(max));
swap(b.at(i), b.at(max));
}
}
void print_usage();
int main(int argc, char *argv[]) {
if (argc != 2) {
print_usage();
}
string junkline;
unsigned int i;
vector<string> timeStamps;
vector<double> latitudes;
vector<double> longitudes;
vector<double> depths;
vector<double> magnitudes;
vector<string> locations;
vector<string> types;
double avgMagnitude;
double avgDepth;
string timeStamp;
double latitude;
double longitude;
double magnitude;
double depth;
string location;
string type;
getline(cin, junkline);
do {
getline(cin, timeStamp);
timeStamps.push_back(timeStamp);
cin >> latitude;
latitudes.push_back(latitude);
cin >> longitude;
longitudes.push_back(longitude);
cin >> magnitude;
magnitudes.push_back(magnitude);
cin >> depth;
depths.push_back(depth);
getline(cin, quoted(location));
locations.push_back(location);
getline(cin, type);
types.push_back(type);
}
while (timeStamp, latitude, longitude, magnitude, depth, location,
type);
avgMagnitude = avg(magnitudes);
avgDepth = avg(depths);
cout << "The average magnitude: " << avgMagnitude << endl;
cout << "The average depth: " << avgDepth << endl;
selection_sort(longitudes, latitudes);
ofstream new_all_month;
new_all_month.open ("sorted data.csv");
new_all_month << "Timestamp, latitude, longitude, magnitude,
depth, location, type" << endl;
for (i = 0; i < timeStamps.size(); i++) {
new_all_month << timeStamps.at(i) << "," << latitudes.at(i) <<
"," << longitudes.at(i) << "," << magnitudes.at(i) << "," <<
depths.at(i) << "," << locations.at(i) << "," << types.at(i) << endl;
}
new_all_month.close();
return 0;
}
然后您可以等待提取