我有以下代码:
var incr = num => new Promise(resolve => {
resolve(num + 1);
});
var x = incr(3)
.then(resp => incr(resp))
.then(resp => console.log(resp));
async function incrTwice(num) {
const first = await incr(num);
const twice = await incr(first);
console.log(twice);
}
incrTwice(6);
Run Code Online (Sandbox Code Playgroud)
我相信(可能是错误的)显示了实现相同功能的两种等效方法:首先通过链接承诺,其次使用 async/await 的语法糖。
我希望promise 链接解决方案首先是console.log,然后是异步函数,但是异步函数console.log 的第一个然后是promise 链接解决方案打印。
我的逻辑如下:
x
s 初始解析将在处理声明时首先出现在微任务队列中x
和的声明之间堆栈是空的,incrTwice
这将导致微任务队列被刷新(导致承诺链的完成)
incrTwice
被定义为incrTwice
在await
s处的微任务队列上执行排队,最终打印到控制台
显然我在某处有误解,有人能够指出我错在哪里吗?
我还在学习JavaScript Promise
,我遇到了一个我不理解的行为.
var o = $("#output");
var w = function(s) {
o.append(s + "<br />");
}
var p = Promise.resolve().then(function() {
w(0);
}).then(function() {
w(1);
});
p.then(function() {
w(2);
return new Promise(function(r) {
w(3);
r();
}).then(function() {
w(4);
});
}).then(function() {
w(5);
});
p.then(function() {
w(6);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
Run Code Online (Sandbox Code Playgroud)
我希望这些语句按顺序运行 - 也就是说,输出就是
0
1
2
3
4
5
6
Run Code Online (Sandbox Code Playgroud)
相反,输出是
0
1
2
3
6
4
5
Run Code Online (Sandbox Code Playgroud)
即使去除内在Promise
也会给我带来矛盾的结果. 1
之前输出2
,但6
之前输出5 …
我正在学习 js 中的 Promise,我对此有一些疑问,这是代码:
Promise.resolve().then(() => {
console.log(0);
return Promise.resolve(4);
}).then((res) => {
console.log(res)
})
Promise.resolve().then(() => {
console.log(1);
}).then(() => {
console.log(2);
}).then(() => {
console.log(3);
}).then(() => {
console.log(5);
}).then(() => {
console.log(6);
})
Run Code Online (Sandbox Code Playgroud)
输出与我预期的相差甚远,我认为它会是 0 1 4 2 3 5 6,因为我在 MDN 上看到了这个
Promise.resolve() 方法返回一个使用给定值解析的 Promise 对象
那么 log() 方法不应该在数字 1 后面触发吗?
我究竟做错了什么?
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let p = sleep(50);
p.then(() => console.log('a')).then(() => console.log('c'));
p.then(() => console.log('b')).then(() => console.log('d'));
Run Code Online (Sandbox Code Playgroud)
这是否保证按顺序打印"a,b,c,d"?
据我所知,"a"必须在"c"之前触发,"b"必须在"d"之前触发,但除此之外,JS解释器是否可以决定以不同的顺序执行余数?