首页 > 解决方案 > 如何在 while(JavaScript/Node.js) 中使用 Promise?

问题描述

我正在尝试使用 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);
  });
}

标签: javascriptnode.jsloopssynchronous

解决方案


.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();


推荐阅读