Skip to content

Instantly share code, notes, and snippets.

@sdjcw
Created April 1, 2017 06:30
Show Gist options
  • Save sdjcw/af8e469f8b594cb297d786b75b17488d to your computer and use it in GitHub Desktop.
Save sdjcw/af8e469f8b594cb297d786b75b17488d to your computer and use it in GitHub Desktop.
LeanCloud JS-SDK 遍历表
const forEachAVObject = (query, fn) => {
let cursor = new Date(0);
const innerFn = () => {
return query
.greaterThan('createdAt', cursor)
.ascending('createdAt')
.limit(1000)
.find()
.then((objs) => {
_.forEach(objs, fn);
if (objs.length === 1000) {
cursor = _.last(objs).get('createdAt');
return innerFn();
}
});
};
return innerFn();
};
// example:
forEachAVObject(new AV.Query('Todo').equalTo('author', 'zhangsan'), (todo) => {
console.log('>>', todo);
})
@hjiang
Copy link

hjiang commented Dec 13, 2017

大部分这种场景都是要修改对象然后写回数据库的,确保所有操作顺序执行会比较好。

const serialForEach = (objs, fn, done) => {
  let last = objs.pop();
  if (last) {
    fn(last, () => { serialForEach(objs, fn, done); });
  } else {
    done();
  }
}

const forEachAVObject = (query, fn) => {
  let cursor = new Date(0);
  const innerFn = () => {
    return query
    .greaterThan('createdAt', cursor)
    .ascending('createdAt')
    .limit(1000)
    .find()
    .then((objs) => {
      cursor = objs[objs.length-1].get('createdAt');
      serialForEach(objs, fn, innerFn);
    });
  };
  return innerFn();
};

这样就可以做批量修改:

  forEachAVObject(new AV.Query('_User').doesNotExist('status'), (user, done) => {
    user.set('status', 'active');
    user.save().then(done);
  })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment