Using the Promise
class
我建议看一看MDN's Promise docs,它为使用promise 提供了一个很好的起点.或者,我相信网上有很多教程.:)
Note:款现代浏览器已经支持ECMAScript 6promise 规范(参见上面链接的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 support.现在可以将函数声明为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
}