So, you can't mix async/await
with plain asynchronous callbacks. They do not work properly. Your async
function getSSN()
is not properly resolving when your request.get()
finishes because that's just a plain asynchronous callback which the async function knows nothing about.
Instead, you need to use a promise-based request()
option. Since, the request library is now deprecated and should not be used for new projects, I would suggest one of the alternatives that are all based on promises already. My favorite is the got()
library, but you can look at the list of alternatives and pick the one that has a programming style you like.
In addition, your getSSN()
function has a bunch of side effects (modifying higher scoped variables). This is not a good way to program, particularly for asynchronous operations because the outside world generally doesn't know when things are done and when the higher scoped variables have the values in them you want them to. You should make getSSN()
return a promise that resolves to its result and then have the caller use that result to modify the higher scoped variables. Again, if you showed us the rest of the coding context here, we could suggest a better overall way to do this. Please notice here that you're just not providing enough code for us to be able to show you the best way to write this code. That should be a general lesson for stackoverflow. Err on the side of giving us more than you think and we can then often make suggestions and improvements far beyond what you even know to ask about.
Here's your function with all the ill-adivsed side effects still in it (because you haven't shown us the rest of the code) using got()
:
async function getSSN(next) {
const result = await got('idms.dealersocket.com/api/account/…').json();
if (count <= totalpage) {
const data = Object.assign({}, result.Data);
const len = Object.keys(data).length;
for (var i = 0; i <= len; i++) {
ssn.push(data[i].Row.Borrower1SSN);
}
count++;
}
}
Now, getSSN()
will return a promise that resolves or rejects when the network request is finished.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…