使用Promise
课程
我建议看一下MDN的Promise文档,它们为使用Promises提供了一个很好的起点。另外,我确定在线上会有很多教程。:)
注意: 现代浏览器已经支持Promises的ECMAscript 6规范(请参阅上面的MDN文档),并且我假设您要使用本机实现,而没有第三方库。
至于一个实际的例子…
基本原理如下:
- 您的API被称为
- 您创建一个新的Promise对象,该对象将单个函数用作构造函数参数
- 您提供的函数由基础实现调用,并且该函数具有两个函数-
resolve
和reject
- 完成逻辑后,您可以调用其中之一来完全履行Promise或因错误而拒绝它
这看起来可能很多,所以这里是一个实际示例。
exports.getUsers = function getUsers () { // Return the Promise right away, unless you really need to // do something before you create a new Promise, but usually // this can go into the function below return new Promise((resolve, reject) => { // reject and resolve are functions provided by the Promise // implementation. Call only one of them. // Do your logic here - you can do WTF you want.:) connection.query('SELECt * FROM Users', (err, result) => { // PS. Fail fast! Handle errors first, then move to the // important stuff (that's a good practice at least) if (err) { // Reject the Promise with an error return reject(err) } // Resolve (or fulfill) the promise with data return resolve(result) }) })}// Usage:exports.getUsers() // Returns a Promise! .then(users => { // Do stuff with users }) .catch(err => { // handle errors })使用异步/等待语言功能(Node.js> = 7.6)
在Node.js 7.6中,v8 Javascript编译器已通过async /
await支持进行了升级。现在,您可以将函数声明为is
async,这意味着它们会
Promise在异步函数完成执行后自动返回一个已解析的。在此函数内,您可以使用
await关键字等待另一个Promise解析。
这是一个例子:
exports.getUsers = async function getUsers() { // We are in an async function - this will return Promise // no matter what. // We can interact with other functions which return a // Promise very easily: const result = await connection.query('select * from users') // Interacting with callback-based APIs is a bit more // complicated but still very easy: const result2 = await new Promise((resolve, reject) => { connection.query('select * from users', (err, res) => { return void err ? reject(err) : resolve(res) }) }) // Returning a value will cause the promise to be resolved // with that value return result}


