Reputation: 45
I need to wait for the task of this API to finish before moving to the next task. How would I add a promise / await to this syntax?
I need to use the enqueue function and then wait for the stream to complete before continuing any further code. I have tried returning a promise withing the .on('end', {}) call but with no luck.
Any help is much appreciated.
const {SiteChecker} = require('broken-link-checker');
const siteChecker = new SiteChecker(options)
.on('error', (error) => {})
.on('robots', (robots, customData) => {})
.on('html', (tree, robots, response, pageURL, customData) => {})
.on('queue', () => {})
.on('junk', (result, customData) => {})
.on('link', (result, customData) => {})
.on('page', (error, pageURL, customData) => {})
.on('site', (error, siteURL, customData) => {})
.on('end', () => {});
siteChecker.enqueue(siteURL, customData);
Upvotes: 1
Views: 1155
Reputation: 2658
Your code is almost fine, but in order to use Promises you need to wrap the whole code in it. You'd achieve that like this:
const {SiteChecker} = require('broken-link-checker');
const siteChecker = new SiteChecker(options)
.on('error', (error) => {})
.on('robots', (robots, customData) => {})
.on('html', (tree, robots, response, pageURL, customData) => {})
.on('queue', () => {})
.on('junk', (result, customData) => {})
.on('link', (result, customData) => {})
.on('page', (error, pageURL, customData) => {})
.on('site', (error, siteURL, customData) => {});
await new Promise((resolve, reject) => siteChecker
.on('end', resolve)
// resolve is a function that you call when the work is done
.on('error' => reject)
// reject is the function you call when the task fails
.enqueue(siteURL, customData);
);
Now I'm not sure how the broken-link-checker
works in your case, but if you wanted to reuse the whole solution then it would be best to wrap the whole thing in the promise and return the siteChecker
reference like this:
const {SiteChecker} = require('broken-link-checker');
const siteChecker = await new Promise((resolve, reject) => {
const _sitechecker = new SiteChecker(options)
.on('error', (error) => {})
.on('robots', (robots, customData) => {})
.on('html', (tree, robots, response, pageURL, customData) => {})
.on('queue', () => {})
.on('junk', (result, customData) => {})
.on('link', (result, customData) => {})
.on('page', (error, pageURL, customData) => {})
.on('site', (error, siteURL, customData) => {});
.on('end', () => resolve(_sitechecker))
// notice that the sitechecker is passed here
.on('error' => reject);
sitechecker.enqueue(siteURL, customData);
});
Both ways of writing this will wait until completion (or until the end
event is emitted).
Upvotes: 1