我的代码是这样的:-
function doStuff(){
// Note:- this funcion take 50ms for ececution as i have put
// timeout
setTimeout(function(){
// some line of code
....
}, 50);
return;
}
doStuff();
console.log('This should execute after doStuff() complete its work.")
// after that more many lines of code and more stuff are here
.....
.....
答案 0 :(得分:2)
您需要使用回调或Promise。这是一个诺言的例子:
function doStuff(){
var promise = new Promise((resolve) => {
// Note:- this funcion take 50ms for ececution as i have put
// timeout
setTimeout(function(){
// some line of code
resolve();
}, 1000);
});
return promise;
}
async function main() {
console.log('Start.');
await doStuff();
console.log('This should execute after doStuff() complete its work.');
}
main();
或者,如果您不想使用ES6带来的不错的.then()
功能,请使用async/await
的Promise:
function doStuff(){
var promise = new Promise((resolve) => {
// Note:- this funcion take 50ms for ececution as i have put
// timeout
setTimeout(function(){
// some line of code
resolve();
}, 1000);
});
return promise;
}
console.log('Start.');
doStuff().then(() => console.log('This should execute after doStuff() complete its work.'));
这是使用回调的示例:
function doStuff(callback){
setTimeout(function(){
// some line of code
callback();
}, 1000);
}
console.log('Start.');
doStuff(function() {
console.log('This should execute after doStuff() complete its work.');
});