Node.js Promise Chain not firing in desired order

问题: I created a simple example of a Promise chain. My goal is to fire the 4 functions below to get the output in Order. i.e. 1 2 3 4. function WriteOne() { return new Pro...

问题:

I created a simple example of a Promise chain. My goal is to fire the 4 functions below to get the output in Order. i.e. 1 2 3 4.

function WriteOne()
{
    return new Promise(function(resolve, reject)
    {
        console.log("1");
        resolve("true");
    })    
}

function WriteTwo()
{
    return new Promise(function(resolve, reject)
    {
        setTimeout(function(){console.log("2");}, 3000);
        resolve("true");
    })    
}

function WriteThree()
{
    return new Promise(function(resolve, reject)
    {
        setTimeout(function(){console.log("3");}, 1000);
        resolve("true");
    })
}

function WriteFour()
{
    return new Promise(function(resolve, reject)
    {
        console.log("4");
        resolve("true");
    }) 
}

WriteOne().then(WriteTwo).then(WriteThree).then(WriteFour);

When I execute them, they are firing in this order:

1 4 3 2

What am I doing wrong here?


回答1:

You need to resolve inside setTimeout callback

function WriteOne() {
	return new Promise(function (resolve, reject) {
		console.log("1");
		resolve("true");
	});
}

function WriteTwo() {
	return new Promise(function (resolve, reject) {
		setTimeout(function () {
			console.log("2");
			resolve("true");
		}, 3000);
		
	});
}

function WriteThree() {
	return new Promise(function (resolve, reject) {
		setTimeout(function () {
			console.log("3");
			resolve("true");
		}, 1000);
		
	});
}

function WriteFour() {
	return new Promise(function (resolve, reject) {
		console.log("4");
		resolve("true");
	});
}

WriteOne().then(WriteTwo).then(WriteThree).then(WriteFour);


回答2:

Nothing wrong here, here what's happening:

// t=0s
writeOne()
// 1 is logged
// promise is resolved
.then(writeTwo)
// in 3s, 2 will be logged
// promise is resolved
.then(writeThree)
// in 1s, 3 will be logged
// promise is resolved
.then(writeFour)
// 4 is logged

// t=1s
// 3 is logged

// t=3s
// 2 is logged

Thus the output.

To get the result you're expecting, resolve the promise inside the setTimeout.


回答3:

resolve("true") is called before the console.log() because it's outside the setTimeout().

Since WriteOne() and WriteFour() have no timeout, "1" and "4" appear first. Then "3" 1 second later, Then 2.

You have to put resolve("true"); inside setTimeout() in order to have them appear... in order.

  • 发表于 2019-01-11 14:47
  • 阅读 ( 177 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除