我遇到了一些异步数据库查询问题。我正在使用Node.js的Async库。我有一些代码在它到达add()函数之前形成一个对象。在我的代码中,我有一个循环执行来多次创建对象。
for(var i = 0; i < 10; i++){
var obj.id = i + '_idstring';
add(obj);
}
如您所见,每个对象都略有不同。我需要在我的数据库中执行查找以查看对象是否已存在(第一个瀑布函数),如果没有,则将其添加到我的数据库(第二个瀑布函数)。我的问题是,loaObj.id总是等于10_idstring。这是我如何通过回调传递对象的问题?我应该怎么处理这个?
function add(loaObj) {
async.waterfall([
function(loaObj, callback) {
var sql = "";
connection.query(sql, function(error, results, fields) {
callback(error, results, loaObj);
});
},
function(results, loaObj, callback) {
if (results.length > 0) {
sendMessage();
} else {
var sql = "";
connection.query(sql, function(error, results, fields) {
callback(error, loaObj);
});
}
}
], function(err, loaObj) {
console.log(err);
if (err) {
sendMessage();
} else {
sendMessage();
}
});
}
答案 0 :(得分:1)
因为您正在使用对象,它将通过&#34;副本引用&#34;,然后import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, combineReducers } from 'redux'
import { connect } from 'react-redux'
import { Field, reduxForm, reducer as form } from 'redux-form'
// ACTION & ACTION CREATOR
const SAVE_FORM = 'SAVE_FORM';
function saveForm(values) {
return {
type: SAVE_FORM,
values
}
}
// REDUCER - save
const INITIAL = { url:'hiiii' };
function save(state=INITIAL, action) {
switch(action.type) {
case SAVE_FORM: return action.values;
default: return state;
}
}
// STORE
const reducers = combineReducers({ form, save });
const store = createStore(reducers);
// MY FORM COMPONENT
class MyFormDumb extends React.Component {
handleReset = e => {
e.preventDefault();
this.props.reset();
}
render() {
console.log('MyFormDumb :: pristine:', this.props.pristine, 'initialValues:', this.props.initialValues);
return (
<form onSubmit={this.props.handleSubmit}>
<label htmlFor="url">URL</label>
<Field name="url" component="input" type="text" />
<button onClick={this.handleReset}>Reset</button>
<button type="submit">Save</button>
</form>
)
}
}
const MyFormControlled = reduxForm({ form:'my-form' });
const MyFormSmart = connect(
function(state) {
return {
initialValues: state.save
}
}
);
const MyForm = MyFormSmart(MyFormControlled(MyFormDumb));
// MY APP COMPONENT
class App extends React.PureComponent {
submitHandler = (values, dispatch, formProps) => {
dispatch(saveForm(values));
}
render() {
return (
<Provider store={store}>
<div className="app">
<MyForm onSubmit={this.submitHandler} />
</div>
</Provider>
)
}
}
// RENDER
ReactDOM.render(<App />, document.getElementById('app'))
将被每个循环覆盖,它将稳定到obj.id
- 循环停止的地方 - 。
一个简单的解决方案是每次都传递新的Object,如下所示:
10_idstring