gpt4 book ai didi

node.js - Sequelize ORM 异步方法调用

转载 作者:太空宇宙 更新时间:2023-11-03 21:53:28 24 4
gpt4 key购买 nike

如何在sequelize ORM中异步调用方法? (因为我必须在其他方法中使用返回值)。

用户.dao.js:

var User = require('./user.model');

class UserDao {
constructor() {}

insert(user) {
var pk;
User.sync({ force: false }).then(() => {
User.create(user).then(function(user) {
console.log('Entry successful from dao: ' +
JSON.stringify(user));
//return generated pk
pk = user.id;
console.log('ID: ' + pk);
});
});
return pk;
}

用户.test.js:

class UserDaoTest {
constructor() {
this.userDao = new UserDao();
this.compare = new UtilsObject();
}

/*
all CRUD method calls
*/
testAll() {
this.testInsert();
this.testUpdate();
//this.testDelete();
//this.testRead();
//this.compare();
}

/*
insert method
*/
testInsert() {
// composite form
var user = {
name: 'nisha',
email: 'nisha@gmail.com',
phoneNo: 8978,
picUrl: 'nisha',
description: 'SI',
status: 'active',
waitingTime: 10,
rating: 7
};

/*
calling insert user with above data
*/
var pk = this.userDao.insert(user);
console.log('pk value: ' + pk);
//var obj1 = this.userDao.readById(pk);
console.log('obj1 value: ' + user);
//this.testReadById(obj1);
}

testReadById(obj1) {
var obj2 = this.userDao.readById(obj1);
this.compare.compare(obj1, obj2);
this.testDelete(obj1);
}
}

export default UserDaoTest;

在 user.test.js 中,在 testInsert() 方法中想要获取从 user.dao.js 的 insert() 方法返回的 pk 值,但现在我得到的 pk 值未定义。

最佳答案

使用 promise 链。假设您需要获取特定用户的条目并对其进行一些操作。

Model.User.findById(someId)
.then((user) => {
// Do something with user.
})

你不应该同步调用方法,NodeJs 不是这样设计的。它与回调或 promise 一起使用。

关于node.js - Sequelize ORM 异步方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47194375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com