如何在 while(JavaScript/Node.js) 中使用 promise?

How to use promise in while(JavaScript/Node.js)?

我正在尝试使用 promise 和 while (JavaScript/Node.js) 按顺序重复执行多个进程。 但是,promise 函数不会被执行(即,所有 console.log() 都不会显示)。

为什么promise函数在while中从来没有执行过?

另外,如何按顺序重复显示一些console.log()?

var count = 0;
while(count < 5) {
  Promise.resolve()
  .then(function () {
    return new Promise(function(resolve, reject) {
      console.log('func1()...');
      resolve('OK');
    });
  })
  .then(function(value) {
    return new Promise(function(resolve, reject) {
      console.log('func2()...');
      resolve('OK');
    });
  })
  .then(function (value) {
    console.log('func3()...');
    count++;
  }).catch(function (error) {
    console.log(error);
  });
}

发生了什么 - 在 Javascript 中,您编写的事件循环和源代码在一个线程中执行。这意味着如果这个线程被某些工作阻塞,则不会执行任何其他操作。 它的工作方式非常简单——事件循环接受一个事件(你展示的代码),它处理所有同步部分,并将任何异步事物(承诺链)推送到事件循环,以便稍后执行。

问题是这样的:

var count = 0;
while(count < 5) {
  Promise.resolve()
  .then(
  // some promise chain...
}

while 陷入永无止境的循环,因为所有同步部分都是将此 Promise 链推入事件循环,然后重新开始。 count 在此上下文中永远不会更改。

最适合你的是使用async/await,不需要深入理解Node.js

就可以解决你想要的问题

另一种选择是使用递归

function promiseChain() {
  return Promise.resolve()
  .then(function () {
    return new Promise(function(resolve, reject) {
      console.log('func1()...');
      resolve('OK');
    });
  })
  .then(function(value) {
    return new Promise(function(resolve, reject) {
      console.log('func2()...');
      resolve('OK');
    });
  })
  .then(function (value) {
    console.log('func3()...');
    count++;
  }).catch(function (error) {
    console.log(error);
  });
}

recursivelyExecute(promise, count) {
  if (count > 5) {
    return;
  }
  count++;
  return promise.then(() => recursivelyExecute(promiseChain(), count+1));
}

.then()仍然是一个异步回调,消息顺序看这里:

Promise.resolve().then(()=>console.log("got resolved"));
console.log("got here");

您可以做的一件事是将代码包装成 async function:

async function test(){
  var count = 0;
  while(count < 5) {
    await Promise.resolve()
    .then(function () {
      return new Promise(function(resolve, reject) {
        console.log('func1()...');
        resolve('OK');
      });
    })
    .then(function(value) {
      return new Promise(function(resolve, reject) {
        console.log('func2()...');
        resolve('OK');
      });
    })
    .then(function (value) {
      console.log('func3()...');
      count++;
    }).catch(function (error) {
      console.log(error);
    });
  }
}

test();

var count = 0;
while(count < 5) {
  Promise.resolve()
  .then(function () {
    return new Promise(function(resolve, reject) {
      console.log('func1()...');
      resolve('OK');
    });
  })
  .then(function(value) {
    return new Promise(function(resolve, reject) {
      console.log('func2()...');
      resolve('OK');
    });
  })
  .then(function (value) {
    console.log('func3()...');
  }).catch(function (error) {
    console.log(error);
  });
  count++;
}

您需要使用 Promise.all()async.eachSeries 进行循环。为此,您需要安装 async 然后执行以下操作:

const async = require('async');
var count = [...Array(5).keys()];
async.eachSeries(count, (c, next) => {
  Promise.all([
    new Promise(function (resolve, reject) {
      console.log('func1()...');
      resolve('OK');
    }), 
    new Promise(function (resolve, reject) {
      console.log('func2()...');
      resolve('OK');
    })]).then(function (values) {
    console.log('func3()...');
    next();
  });
}, (err) => {
  console.log("here we done");
});