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

时间:2016-04-27 12:20:23

标签: javascript promise

代码:

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在调用下一个then回调之前没有等待解决?

JSFiddle https://jsfiddle.net/puhbqtu0/1/

1 个答案:

答案 0 :(得分:5)

因此,如果您希望在系列中运行promises,则应将x转换为函数并在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 demo