javascript - JavaScript:停止执行直到延迟结束
问题描述
我的代码是这样的: -
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
.....
.....
- 现在我想要的是,正如您在此处看到的那样,doStuff() 需要 50 毫秒的时间来执行,因此 doStuff() 之后的代码应该在 doStuff() 完成后执行。例如,该控制台应该在 doStuff() 完成后打印。
- 请注意,我知道我可以将 timeOut 放在那里,但由于一些限制,我无法设置 timeout,因为我正在开发一个开源项目,所以我无法更改在该函数调用之后编写的代码,我什至不能等待正如我所说的那样,我无法更改该代码,我能做的就是更改我创建的 doStuff 方法。有什么方法可以阻止 doStuff() 返回,就像 doStuff() 在延迟结束之前不应该返回,一种方法是我们可以递归调用 doStuff 但我想要更好的方法来做到这一点。请帮帮我。
解决方案
您要么需要使用回调,要么需要使用 Promise。下面是一个 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();
或者,.then()
如果您不想使用async/await
ES6 带来的出色功能,可以使用 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.');
});
推荐阅读
- python - Python3:如何根据元组字典生成表
- c# - .Net 控制台应用程序 - 如果有多个服务,则调用特定服务
- python - 如何为 Pandas pd.read_csv 设置代理
- r - 计算两个日期之间的月份天数
- java - GraphQL 和 Spring Boot 2.0.3
- ios - iPhone 相机在 react-native 0.55.4 中不起作用?
- c# - 是否可以存储正则表达式匹配并将其中的一部分用作列表枚举器?
- objective-c - How to log the current function name in Dart?
- ios - 如何使用 Swift 4 设置 UITextField 边框从左到右的渐变和圆角
- git - 进行bitbucket合并时如何省略一些代码