[英]How can i call a function after completion of another function if the another function takes more time?
I am trying to apply callbacks in javascript, this is a sample code analogous to a piece of code something in my website built in node.js我正在尝试在 javascript 中应用回调,这是一个示例代码,类似于我在 node.js 中构建的网站中的一段代码
var a = function(obj,callback){
var p = {name: 'name', age: 35}
obj.p = p
setTimeout(function(){
console.log("waiting for three seconds");
}, 3000);
console.log("...................")
callback(obj)
}
var b = function(obj){
var q = {name: 'name2', age: 37}
obj.q = q
console.log("*******************")
}
var func = function(){
var obj = {};
a(obj,b)
console.log(obj)
}
func()
on running this code i get the output: -在运行这段代码时,我得到了 output:-
...................
*******************
{ p: { name: 'name', age: 35 }, q: { name: 'name2', age: 37 } }
waiting for three seconds
Now here, in the function "a" the line "waiting for three seconds" is printed after 3 seconds in that time the callback function is also called, hence the line "waiting for three seconds" is printed after the output of function "b" ie is "****************"现在在这里,在 function "a" 中,在 3 秒后打印了 "waiting for three seconds" 行,此时回调 function 也被调用,因此在 output of function "b" 之后打印了行 "waiting for three seconds" “即是”******************“
However i want the output to be this但是我希望 output 是这个
waiting for three seconds
...................
*******************
{ p: { name: 'name', age: 35 }, q: { name: 'name2', age: 37 } }
How can i achieve this?我怎样才能做到这一点? kindly help i am stuck here.
请帮助我被困在这里。
You can use make use of JavaScript promises to achieve the synchronisation.您可以使用 JavaScript 承诺来实现同步。 Change your code like below.
像下面这样更改您的代码。
We have wrapped up all the async operations inside promise. await will hold on the execution until the promise is resolved.我们已经完成了 promise 中的所有异步操作。await 将暂停执行,直到 promise 被解析。
var a = async function(obj) {
var p = {name: 'name', age: 35}
obj.p = p
await timeout( 3000)
console.log("...................")
b(obj)
}
var b = function(obj) {
var q = {name: 'name2', age: 37}
obj.q = q
console.log("*******************")
}
function timeout(ms) {
return new Promise(resolve =>
setTimeout(function(){
console.log("waiting for three
seconds");
resolve()
}, ms));
}
var func = async function(){
var obj = {};
await a(obj,b)
console.log(obj)
}
func()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.