Oh, man.
0. Error description
I made a rather serious mistake in development today
For incorrect use of Promise
Scene.
Displaying a list of search terms in a WeChat app
// API Request Tool Functions
const apiRequest = (url, method = 'GET', headers = {}) => {
return new Promise((resolve, reject) => {
({
url,
method,
header: headers,
success: (res) => resolve(res),
fail: (error) => reject(error)
});
});
};
const fetchTypelist = async () => {
const app = getApp();
const queryParams = ;
(queryParams)
let url = `${API_BASE_URL}/industryType/page?pageNo=1&pageSize=10`;
// Add regular query parameters
for (const [key, value] of (queryParams)) {
if (value) {
url += `&${key}=${encodeURIComponent(value)}`;
}
}
try {
const headers = {}; // If you need a token, you can add it here.
const response = await apiRequest(url, 'GET', headers);
if ( === 200) {
()
return response
} else {
throw new Error('Failed to get address list');
}
} catch (error) {
throw error;
}
};
/.................../
invoke a method
let result= fetchTypelist()
(result)
Guess what's gonna be printed?
A promise is just a promise, it doesn't get the result of the request.
1. Analyze
async
function by default returns aPromise
Even if you're inasync
value is explicitly returned in the function.
When you call the function defined by async(fetchTypelist)
when it returns what is actually aPromise
, rather than directly returned data.
2. Solutions
2.1. Use await to wait for a method to execute and get the return value.
const getTypelist = async () => {
try {
const typelist = await fetchTypelist();
(typelist); // Here you can get the rows returned
} catch (error) {
(error); // process error
}
};
2.2. using chained calls.then() for promises
fetchTypelist()
.then((typelist) => {
(typelist);
})
.catch((error) => {
(error);
});
3. Successful acquisition