Lea*_*cim 0 javascript node.js promise
承诺的第二部分(内部then)永远不会运行.当我在不使用Promise的情况下运行数据库查询时(在我运行的节点脚本中,node myscript.js它返回数据,但控制台永远不会返回提示 - 控制台只是挂起,我必须手动发送一个中断.因此,当我把它放在Promise中,我认为Promise不知道数据库查询是否完整,即使它似乎已经返回了所有数据,因此Promise的第二部分没有运行(我想).如果这是问题,如何编写数据库查询以使其不挂起并且Promise可以运行完成?
const sqlite = require('/usr/local/lib/node_modules/sqlite3');
const express = require('/usr/local/lib/node_modules/express')
const promise = require('/usr/local/lib/node_modules/promise')
app.get('/', (request, res) => {
var res = [];
function getData() {
return new Promise(function(resolve, reject) {
db.each('SELECT column_a, column_b FROM trips group by column_a', (e, rows) => {
var d = {
a: rows['column_a'],
b: rows['column_b']
}
res.push(d)
});
});
}
getData().then(function(data) {
console.log("never run....", res, data) //never run
});
})
Run Code Online (Sandbox Code Playgroud)
您需要通过调用它的构造函数调用它在回调中提供的函数来解析promise.
const promise = new Promise((resolve, reject) => {
// you must call resolve() or reject() here
// otherwise the promise never resolves
});
Run Code Online (Sandbox Code Playgroud)
否则它将始终处于Pending状态,并且永远不会调用您传入的回调then.
promise.then(() => {
// this never gets called if we don't resolve() or reject()
});
Run Code Online (Sandbox Code Playgroud)
此外,promises允许您使用值来解析,因此通常不需要维护全局变量,您只需传递结果即可.
最后,db.each将为每一行调用一次回调函数,因此您需要通过在获得所有行后解析promise来处理它
以下是编写代码的方法:
function getData() {
const data = [];
return new Promise((resolve, reject) => {
db.each('SELECT column_a, column_b FROM trips group by column_a', (e, row) => {
if (e) {
// error reading a row, reject the Promise immediately
// optionally you could accumulate errors here in a similar manner to rows
reject(e);
return;
}
// success reading a row, store the row result
data.push({
a: row['column_a'],
b: row['column_b']
});
}, (e, rowCount) => { // the complete handler called when the operation is done, see docs: https://github.com/mapbox/node-sqlite3/wiki/API#databaseeachsql-param--callback-complete
if (e) {
// operation finished, there was an error
reject(e);
return;
}
// operation succeeded, resolve with rows
resolve(data);
});
});
}
app.get('/', (request, res) => {
getData().then((data) => {
// here `data` is an array of row objects
}, (e) => {
console.error(`Database error: ${e}`);
});
});
Run Code Online (Sandbox Code Playgroud)
边注
不知道为什么你重新声明参数res为[],但有没有必要做var res = [].既然你已经有了res,你可以说res = []要指向res一个新的数组.当然,这将覆盖响应对象,因此我假设您只是为了本示例的目的而这样做.如果没有,您应该创建一个新变量.
| 归档时间: |
|
| 查看次数: |
514 次 |
| 最近记录: |