如何在javascript中wait Promise.all.then之后调用代码?
举个例子: js如何在javascript中wait Promise.all.then之后调用代码?,javascript,node.js,npm,promise,es6-promise,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 funct
"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
为什么
之后在加载完成之前打印?您需要等待池中的承诺。使用实例.createPage()中的
这已经过测试。正在发生的是pool.use
没有等待instance.createPage()
的承诺来解决。您必须返回
承诺,或者等待
承诺。您已经将它的包装器作为一个async
函数,因此最好是一致的,等待它。不熟悉“幻影池”,但看起来您并没有从实例返回承诺。createPage()
…已经被这么多次咬了…去打字吧!我不这么认为,是从中获取的instance.createPage()
,应该返回一个Promise
。是的,但您没有返回该承诺,即您没有return instance.createPage()
。如果希望箭头函数自动返回,则需要删除周围的大括号{}
是的,但有一点不同。它们正在使用处理程序中等待承诺,因此,直到它们完成后才会返回。你不是。您应该返回
或等待
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");
}());