Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

node.js - Problem to use my Callback function in using "For"?

My code:

console.log('Start')
getMember((member) => { console.log(member) })
console.log('End')

function getMember(next) {
    for (let index = 0; index < 1000000000; index++) {
        // Simulation setTimeout()
    }
    next('In getMember')
}

Return:
Start
In getMember
End

I thought I had the following result (see below) but it doesn't, can you explain me?

Return:
Start
End
In getMember

Thanks,

Yves


question from:https://stackoverflow.com/questions/65540704/problem-to-use-my-callback-function-in-using-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
console.log('Start')
function resolveAfter2Seconds() {
    return new Promise(resolve => {
        // setTimeout(() => { resolve('resolved') }, 2000);
        for (let index = 0; index < 1000000000; index++) { }
        resolve('resolved !');
    })
};

async function asyncCall() {
    console.log('calling');
    const result = await resolveAfter2Seconds();
    console.log(result);
}

asyncCall();

console.log('End');

Return:
Start
calling
End
resolved !

I have the impression that promises handle callbacks better !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...