[英]How to make functions execute synchronously in javascript? or how to make functions execute one after another?
Here is my function这是我的 function
function two(){
console.log('two')
}
function one(callback){
setTimeout(()=>{
console.log('one')
},2000)
callback()
}
one(two)
Actual output:实际 output:
two
one
My expected Output:我预期的 Output:
one
two
My question is how to make changes to these functions so that function two() will be executed after function one()我的问题是如何更改这些函数,以便在 function one() 之后执行 function two()
You could simply call the callback()
in your setTimeout
's anonymous function like so:您可以简单地在
setTimeout
的匿名 function 中调用callback()
,如下所示:
function two() { console.log('two') } function one(callback) { setTimeout(() => { console.log('one'); callback(); // execute callback after everything in setTimeout is executed }, 2000); } one(two);
... or, instead, you can use a Promise
with ES7's async/await (or using a .then()
callback) capabilities like so: ...或者,您可以使用
Promise
和 ES7 的async/await (或使用.then()
回调)功能,如下所示:
function two() { console.log('two') } async function one(callback) { // make async so we can use `await` await new Promise((resolve, rej) => { // wait for the promise to resolve... setTimeout(() => { console.log('one'); resolve(); }, 2000) }); callback(); //... then execute the callback } one(two);
This works这有效
let one = new Promise((resolve, reject) =>{
setTimeout(()=>{
console.log('one')
resolve(true)
},2000)
})
one.then((value) => {
console.log('two')
})
I think callback will be called before other execution.This also works.我认为回调将在其他执行之前被调用。这也有效。
function two(){
console.log('two')
}
function one(one, callback){
console.log(one);
callback()
}
one('one', two);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.