繁体   English   中英

承诺在下一次之前不等待解决

[英]Promise not waiting to resolve before next then

码:

var x = new Promise((resolve, reject) => {
    setTimeout( function() {
        console.log( 'x done' );
        resolve()
    }, 1000 );
});


Promise.resolve().then(x).then((resolve, reject) => {
    console.log( 'all done' );
});

输出:

all done
x done

预期产量:

x done
all done

为什么许x不等待调用next之前解决then回调?

JSFiddlehttps//jsfiddle.net/puhbqtu0/1/

因此,当你想在一个系列中运行promises时,你应该将x转换为function并在then调用它:

function x() {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('x done');
      resolve()
    }, 1000);
  });
});

Promise.resolve()
  .then(x)
  .then(() => console.log('all done'));

或最简单的变体:

x().then(() => console.log('all done'));

jsfiddle演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM