Promise中的代码执行和使用返回语句
在这里,虽然使用诺言,我应该需要返回resolve
和reject
方法
代码执行顺利,但如果有多个条件语句,则会reject
和resolve
自动结束,或者我们必须使用返回语句
const getJobs = (filters, fieldASTs) => new Promise((resolve, reject) => { const AST = fieldASTs.fieldNodes[0].selectionSet.selections[0] .selectionSet.selections[0].selectionSet.selections; const FIELDS = _.map(AST, n => n.name.value); if (_.includes(FIELDS, 'employer')) { Job.find(filters, (err, d) => { if (err) return reject(err); // should i need to return or just use reject if (err === null && d === null) return reject(null); // return resolve(d) or only resolve() return resolve(d); }); } else { Job.find(filters, (err, d) => { // here also if (err) return reject(err); // here too return resolve(d); }); } });
是否使用return
语句完全取决于函数中所需的控制stream。 它实际上与承诺没有任何关系。 如果你不想要或者需要在你的函数中执行更多的代码,并且你还没有完全被一个条件隔离,那么使用return
来退出函数。 同样的问题,无论你是否使用承诺。
记住,所有的resolve()
或者reject()
都是改变promise的状态(假设它处于挂起状态),然后调度任何.catch()
或.catch()
处理程序,以便在当前运行后执行Javascript将控制权返回给系统。 它们只是像其他函数调用一样的函数调用。
调用resolve()
或reject()
之后,您不必使用return语句。
所以, return
语句是否合适完全取决于你的代码。 如果你不想在该块中执行更多的代码,然后return
。 如果你不想浪费时间去潜在地调用块中其他地方的resolve()
或reject()
(这实际上不会对promise做任何事情),那么就使用return
。 如果你的代码已经在一个条件块中,而其他的都不会执行,你不想执行,那么就不需要return
。
例如,在你的代码的这一部分:
if (_.includes(FIELDS, 'employer')) { Job.find(filters, (err, d) => { if (err) return reject(err); if (err === null && d === null) return reject(null); return resolve(d); }); }
使用return
是合适的,因为不需要在当前函数中执行更多的代码。 如果你在那里省略了return
,你的代码仍然可以正常工作(在这种情况下),因为在你已经拒绝或解决了承诺之后,你将运行的额外代码实际上不会做任何事情,因为调用了reject()
或resolve()
不会改变任何东西。 但是,我认为让代码运行并不需要运行是浪费和混乱的做法。 所以,在这种情况下,我总是会使用return
或者conditional。
就个人而言,我可能会写这样的代码:
if (_.includes(FIELDS, 'employer')) { Job.find(filters, (err, d) => { if (err) return reject(err); if (d === null) return reject(new Error("unexpected null result from Job.find()")); return resolve(d); }); }
注意:我删除了if (err === null)
的检查,因为这应该是成功的例子。
或者,我会在更低层次上普遍使用Job.find()
,所以我的逻辑stream程都是承诺。