等待promise.all完成

时间:2022-10-30 20:09:18

I have to read, compile multiple jade files and then use the these files. I'm using bluebird promises library with the below code:

我必须阅读,编译多个玉文件,然后使用这些文件。我正在使用bluebird promises库,代码如下:

var indexJadeFile = 'template/index.jade';
var otherJadeFile = 'template/other.jade';

function readAndCompileJade(jadeFile){
    fs.readFileAsync(jadeFile, 'utf8').then(function(content){
        console.log('reading jade file: ' , jadeFile);
        return jade.compile(content, {
            pretty   : true,
            filename : jadeFile,
            basedir  : templateBaseDir
        });
    })
}

promise.all([
    readAndCompileJade(indexJadeFile),
    readAndCompileJade(postJadeFile),
    readAndCompileJade(sitemapJadeFile),
    readAndCompileJade(archivesJadeFile)])
    .then(function(results){
    console.log('results block');
        compiledIndex    = results[0];
        compiledPost     = results[1];
        compiledSitemap  = results[2];
        compiledArchives = results[3];
    });

I assumed that then block will be executed after all the jade files are executed. But when I execute, I find that the results block is printed before reading jade file statements.

我假设在执行所有jade文件之后将执行block。但是当我执行时,我发现在读取jade文件语句之前会打印结果块。

How do I wait for all promises to be completed and then execute the rest of the block?

我如何等待所有承诺完成然后执行其余的块?

1 个解决方案

#1


3  

That's because your readAndCompileJade is synchronous and does not return a promise.

那是因为你的readAndCompileJade是同步的,不会返回一个promise。

You have to return a promise.
How should promise.all know when it should continue?

你必须回复一个承诺。 promise.all应该知道什么时候应该继续?

In your case I assume that fs.readFileAsync is promise based as you use .then so you can just return it:

在你的情况下,我假设fs.readFileAsync是基于你使用.then的承诺,所以你可以返回它:

function readAndCompileJade(jadeFile){
   return fs.readFileAsync(jadeFile, 'utf8').then(function(content){
    console.log('reading jade file: ' , jadeFile);
    return jade.compile(content, {
      pretty   : true,
      filename : jadeFile,
      basedir  : templateBaseDir
    });
  })
}

#1


3  

That's because your readAndCompileJade is synchronous and does not return a promise.

那是因为你的readAndCompileJade是同步的,不会返回一个promise。

You have to return a promise.
How should promise.all know when it should continue?

你必须回复一个承诺。 promise.all应该知道什么时候应该继续?

In your case I assume that fs.readFileAsync is promise based as you use .then so you can just return it:

在你的情况下,我假设fs.readFileAsync是基于你使用.then的承诺,所以你可以返回它:

function readAndCompileJade(jadeFile){
   return fs.readFileAsync(jadeFile, 'utf8').then(function(content){
    console.log('reading jade file: ' , jadeFile);
    return jade.compile(content, {
      pretty   : true,
      filename : jadeFile,
      basedir  : templateBaseDir
    });
  })
}