Today, I encountered a complicated problem when writing code. After simplification, I summarized it as follows:
example: now we have encapsulated two function interfaces, the timeout delay function and the output function. The requirement is to call the above two encapsulated interfaces in the third function eachTest according to the requirement. The code is as follows:
function timeout (millisec) {
const timeo = new Promise(function(resolve, reject){
if (typeof millisec != "number") {
reject("");
}
setTimeout(function () {
resolve(`${millisec}`)
}, millisec)
});
return timeo;
}
function output (millisec, callback) {
timeout(millisec).then(function (result) {
callback(result);
})
}
< H2 > the code I wrote (requires a loop): < / H2 >
async function eachTest () {
let arr = []; //
for (let i = 0; i < 5; iPP) {
await output(1000, function (res) {
arr.push(res); // output
//
});
}
return arr;
}
eachTest().then(function(res){
// eachTest
console.log(res);
})
< H2 > my problem? < / H2 >
most of the problems are written in the comments above. Let"s put it briefly here:
I need to enter the array I need after the function eachTest (). Then
, but every time I find that the first output is arr= []
, that is, the empty array, that is, the then, is executed first (am I guessing the problem of promise nesting here? It"s not the data I need to fill the array, maybe it"s because I"m not familiar with async enough to find a solution myself.
PS: my personal understanding of the solution is to add the async
keyword before function ouput
, but we abandoned this solution with the idea of not changing the original function interface.
ask the gods, is there a better solution to my needs? thank you!