javascript - 从 knex-promise 中获取值(value)

标签 javascript node.js

我有以下功能 - 来自库 knex - 返回一个 promise :

function findById(id) {
    knex('posts').select().where('id', id).first().then(data => {
        return data
    }).catch((err) => console.log(err));
}

const id = 1
        console.log("Post with " + id + ": " + service.findById(parseInt(id)))

但是,我收到以下错误消息:

Post with 1: undefined
ReferenceError: id is not defined

对我做错了什么有什么建议吗?我是否创建了 promise false 的回调?

感谢您的回复

最佳答案

您不能在 javascript 的 promise 中返回值。

为什么?

因为 promise 是异步的。

程序的执行顺序是

console.log("Post with " + id + ": " + undefined) //Because promise haven't return value yet
knex('posts').select().where('id', id).first().then(data => {
        return data
    }).catch((err) => console.log(err));

您在这里可以做的是在 then block 中做一些事情。

function findById(id) {
    knex('posts').select().where('id', id).first().then(data => {
        console.log(data);
    }).catch((err) => console.log(err));
}

如果想把逻辑分离到外面,可以传一个回调函数:

function findById(id, callback) {
    knex('posts').select().where('id', id).first().then(data => {
        callback(data)
    }).catch((err) => console.log(err));
}

const id = 1
service.findById(parseInt(id), (data)=>{
    console.log(data);
})

关于javascript - 从 knex-promise 中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286826/

相关文章:

JavaScript:以 mm/dd/yyyy 格式拆分和连接日期

javascript - 如何比较这两个函数之间的值?

javascript - 仅定义 mongoose 和 Schema

node.js - NTLM 如何为 Web 服务工作以验证用户身份?

javascript - 在 JavaScript 中创建和操作带下划线的对象

javascript - 在浏览器中使用带有外部 URL 的动态导入

javascript - socket.io 无法在服务器上工作并出现 404 错误

node.js - 错误 : The process "node.exe" not found

javascript - 使用 node.js 或 javascript 在后端读取套接字 API

javascript - "Import in body of module; reorder to top import/first"跨多个文件