Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - 稍后在Promise上添加on子句(add on clause later on Promise)

I'm new to Javascript and Promise.(我是Java和Promise的新手。)

I can understand when a Promise has on clause immediately as:(我可以理解Promise何时立即具有on子句,如下所示:) //example 1 var promise1 = new Promise(function(resolve, reject) { console.log("Hi") resolve("World") }).then(function(value) { console.log(value); }); but if the then clause is in separate statement as:(但如果then子句在单独的语句中为:) //example 2 var promise1 = new Promise(function(resolve, reject) { console.log("Hi") resolve("World") }); //at time t here promise1.then(function(value) { console.log(value); }); console.log("Hello"); then I'm a little bit confused because technically speaking, the statement before time t has already been executed, and when the resolve("World") get called, since there is no then clause "registered", so nothing should happen.(那么我有点困惑,因为从技术上讲,时间t之前的语句已经执行,并且当resolve("World")被调用时,因为没有then子句”被注册,所以什么也不会发生。) After time t, promise1.then(...) executes, and it should not know that resolve("World") has been called.(在时间t之后, promise1.then(...)执行,并且它不应该知道resolve("World")已被调用。) But the actual output does show that it know resolve("World") has been called.(但是实际输出确实表明它知道resolve("World")已被调用。) So does it mean that the compiler does sth to assist here?(那么这是否意味着编译器确实可以在此提供帮助?) for example, the compiler merge the then clause right after the promise1 statement just like example 1?(例如,编译器像示例1一样在promise1语句之后合并then子句?)   ask by secondimage translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This happens because the Promise object holds its state internally .(发生这种情况是因为Promise对象在内部保持其状态。)

So when you call .then on a Promise object it will either :(因此,当您在Promise对象上调用.then时,它将:) Await for resolution, and then fire the callback(等待解析,然后触发回调) If the promise is already resolved, the callback will execute immediately(如果承诺已经解决,则回调将立即执行)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...