Just a quick question of clarifications: is JavaScript Promise
asynchronous? I've been reading a lot of posts on Promise
and async programming (namely ajax requests). If Promise
is not async, how do we make it so?
For example, I have a function to wrap a function f
with argument array args
inside a Promise
. Nothing about f
inherently is async.
function getPromise(f, args) {
return new Promise(function(resolve, reject) {
var result = f.apply(undefined, args);
resolve(result);
});
}
To make this async, I read some SO posts and decided that the setTimeout
is what a lot of people were recommending to make code non-blocking.
function getPromise(f, args) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
var r = f.apply(undefined, args);
resolve(r);
}, 0);
});
}
Would this approach with setTimeout
work to make code non-blocking inside a Promise
?
(Note that I am not relying on any third-party Promise API, just what is supported by the browsers).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…