JavaScript
x
18
18
1
function process () {
2
return new Promise((resolve, reject) => {
3
4
5
//make sure module exists
6
let module = modules[queueData.module];
7
if (!module) reject('module not found: '+queueData.module);
8
9
//make sure processor exists
10
let processor = fileProcessors[module.type];
11
if (!processor) reject('processor not found: '+module.type);
12
13
return anotherPromiseFunction();
14
})
15
}
16
17
processFile().catch(e => console.error)
18
anotherPromiseFunction() returns a promise. normally inside a .then() I can return a promise to make the then() wait for that promise to finish, but how do I do it when creating a promise?
Am I supposed to do this:
JavaScript
1
4
1
anotherPromiseFunction()
2
.then(e=>resolve(e))
3
.catch(e=>reject(e))
4
That seems wrong…
Advertisement
Answer
You likely do not need the new Promise
. The cases for “module exists” and “processor exists” can be handled separately, and then you can just return the call to anotherPromiseFunction
after them:
JavaScript
1
14
14
1
//make sure module exists
2
let module = modules[queueData.module];
3
if (!module) {
4
return Promise.reject(new Error('module not found: '+queueData.module));
5
}
6
7
//make sure processor exists
8
let processor = fileProcessors[module.type];
9
if (!processor) {
10
return Promise.reject(new Error('processor not found: '+module.type));
11
}
12
13
return anotherPromiseFunction();
14
If the enclosing function is an async function, you can just throw the errors instead:
JavaScript
1
16
16
1
async function run() {
2
//make sure module exists
3
let module = modules[queueData.module];
4
if (!module) {
5
throw new Error('module not found: '+queueData.module);
6
}
7
8
//make sure processor exists
9
let processor = fileProcessors[module.type];
10
if (!processor) {
11
throw new Error('processor not found: '+module.type);
12
}
13
14
return anotherPromiseFunction();
15
}
16