Run JavaScript promises in order. One after the ot

2019-09-24 18:44发布

This question already has an answer here:

I am trying to run to promises (which make some rest API calls on each). Based on the result of the two promises, use the third function to process the data. Also, the functions running in sequence can be changing. So I made them in a dynamic way of constructing promise.

However, the promises seem to be starting without the previous one ending. Here is a simplified model for testing the same concept.

var funcs = [
	() => {
    console.log('Task 1 Sart =', new Date());
  	sleeper(6000, 'Task 1  Resolved');
    console.log('Task 1  Return');
  },
  () => {
  console.log('Task 2  Sart=', new Date());
  	sleeper(5000, 'Task 2  Resolved');
    console.log('Task 2  Return');
  },
  () => {
  console.log('Task 3  Start=', new Date());
  console.log('Task 2  Return');
  }
];

function sleeper(m, msg) {
	return new Promise(function(resolve, reject) {
  	setTimeout(function() {
    resolve(console.log(msg, new Date()));
  	}, m);
	});
}

function runSequence(functionSequence) {
   return functionSequence.reduce((p, func) => {
       return p.then(func);
   }, Promise.resolve());
} 

var v = runSequence(funcs);

The results look like this VM128:51 Task 1 Sart = Wed Jun 07 2017 13:54:34 GMT-0700 (PDT) VM128:53 Task 1 Return VM128:56 Task 2 Sart= Wed Jun 07 2017 13:54:34 GMT-0700 (PDT) VM128:58 Task 2 Return VM128:61 Task 3 Start= Wed Jun 07 2017 13:54:34 GMT-0700 (PDT) VM128:62 Task 2 Return VM238:69 Task 2 Resolved Wed Jun 07 2017 13:54:39 GMT-0700 (PDT) VM238:69 Task 1 Resolved Wed Jun 07 2017 13:54:40 GMT-0700 (PDT)

I would assume I don't see the second task start till the first one ended. Looked like they all started in sequence. Is anything I missed or totally misunderstand how the promises work. What I tried to achieve is to have the first one completed and then the following starts

1条回答
冷血范
2楼-- · 2019-09-24 19:07

Based on the comments. Here is the version works. A simple return is missing from original codes

var funcs = [
	() => {
    console.log('Task 1 Sart =', new Date());
  	return sleeper(7000, 'Task 1  Resolved');    
  },
  () => {
  	console.log('Task 2  Sart=', new Date());
  	return sleeper(3000, 'Task 2  Resolved');
  },
  () => {
  console.log('Task 3  Start=', new Date());
  console.log('Task 3  Return');
  }
];

function sleeper(m, msg) {
	return new Promise(function(resolve, reject) {
  	setTimeout(function() {
    resolve(console.log(msg, new Date()));
  	}, m);
	});
}

function runSequence(functionSequence) {
   return functionSequence.reduce((p, func) => {     
     return p.then(func);
   }, Promise.resolve());
} 

runSequence(funcs);

查看更多
登录 后发表回答