alh*_*alh 1 javascript node.js
var wait = function() {
return setTimeout(function() {
return 8;
}, 1000);
}
var foo = function() {
if (wait() === 8) {
return 99;
} else {
return 23;
}
}
console.log(foo());
Run Code Online (Sandbox Code Playgroud)
打印23
我理解函数调用是异步的; 但是,if wait()函数如何在函数返回之前进行求值?我试图实现的逻辑如何在javascript中成功表示?
我理解函数调用是异步的;
函数调用完全同步.
在wait()函数返回之前,如何评估if块?
您的wait函数会立即返回setTimeout的结果,即Timeout ID.传递给setTimeout的函数将在以后的某个时间执行,返回值将丢失.
我试图实现的逻辑如何在javascript中成功表示?
您可能正在寻找的代码是这样的.我已将您的代码手动转换为Continuation Passing Style
// `wait` takes a callback which is captured in it's closure to be used by
// the anonymous function passed to setTimeout, sometime in the future.
var wait = function(callback) {
return setTimeout(function() {
callback( 8 );
}, 1000);
}
// `foo` also takes a callback that will be called when the function passed
// to `wait` is evaluated.
var foo = function(callback) {
wait(function(value){
if (value === 8) {
callback( 99 );
} else {
callback( 23 );
}
}
}
// Finally, `foo` is called with another callback, this time logging the value.
foo(function(value) {
console.log(value);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |