如何在javascript中等待Promise.all.then后调用代码?

时间:2017-08-08 03:53:50

标签: javascript node.js npm promise es6-promise

考虑例子:

JS

"use strict";

const input = [
    "https://www.google.ru",
    "https://www.google.ru",
    "https://www.google.ru",
    "https://www.google.ru",
    "https://www.google.ru"
];
const createPhantomPool = require('phantom-pool');
(async function() {
    console.log("start");
    const pool = createPhantomPool({max: input.length*2, min: input.length*2});
    let promises = [];
    input.forEach(url => promises.push(pool.use(async (instance) => {
        instance.createPage()
            .then(page => {
                return page.open(url);
            }).then(() => console.log("load finished"))
            .catch(error => {
                console.log(error);
            });
    })));
    await (Promise.all(promises).then(() => console.log("after then")));
    console.log("end");
}());

的package.json

"dependencies": {
  "aws-sdk": "^2.68.0",
  "es6-promise": "^4.1.0",
  "log4js": "^1.1.1",
  "moment-timezone": "^0.5.13",
  "phantomjs": "^2.1.7",
  "webpage": "^0.3.0"

我预计所有承诺都将完成,并且仅在调用console.log("after then")之后。但是这个例子给了我以下输出:

start
after then
end
load finished
load finished
load finished
load finished
load finished

为什么在after then ???

之前打印load finished

1 个答案:

答案 0 :(得分:1)

您需要await来自pool.use

instance.createPage()承诺"use strict"; const input = [ "https://www.google.ru", "https://www.google.ru", "https://www.google.ru", "https://www.google.ru", "https://www.google.ru" ]; const createPhantomPool = require('phantom-pool'); (async function() { console.log("start"); const pool = createPhantomPool({max: input.length*2, min: input.length*2}); let promises = []; input.forEach(url => promises.push(pool.use(async (instance) => { await instance.createPage() .then(page => { return page.open(url); }).then(() => console.log("load finished")) .catch(error => { console.log(error); }); }))); await (Promise.all(promises).then(() => console.log("after then"))); console.log("end"); }());
pool.use

这已经过测试。发生了什么instance.createPage()不等待return解决的承诺。您要么await承诺,要么async承诺。您已经将它的包装器作为await函数使用,因此可以保持一致并且du -hsc * | sort -h 它。