首页 > 关于node.js异步调用顺序问题

关于node.js异步调用顺序问题

我在向mongodb插入几十条记录的过程中发现一个问题,也就是不知道什么时候插完毕,代码如下:

 var tmp1=JsonObj.RECORDS;
  collection.insertMany(tmp1, {safe: true}, function (err, result) {
                            console.log('----111111!');
                        });
                    console.log('----22222222!');
                                   

发现最先输出的是 “----22222222!”
如何控制必须先输出“-----11111111!”之后才是“------222222!”呢?因为有时候必须得这样做。
初学者诚心求助,谢谢。


console.log('----22222222!');放到回调函数里面,console.log('----111111!');的后面。


Promise....


标准的异步问题:(提供几种解决方案)

  1. 回调

  2. 事件

  3. promise

  4. 生成器CO库

  5. Es7 的 async 异步库


用async流程控制


不知道你用的是什么库。

刚翻了下 node-mongodb-native 的源码:https://github.com/mongodb/node-mongodb-native/blob/2.1/lib/collection.js

其中第516行:

define.classMethod('insertMany', {callback: true, promise:true});

注意这里的 promise: true。也就是说,方法insertMany是支持promise的,再往上看几行:

  // Return a Promise
  return new this.s.promiseLibrary(function(resolve, reject) {
    bulkWrite(self, operations, options, function(err, r) {
      if(err) return reject(err);
      resolve(mapInserManyResults(docs, r));
    });
  });

Return a Promise! Return a Promise! Return a Promise! 重要的事情说三遍!!!

也就是说你的代码可以写成:

var tmp1=JsonObj.RECORDS;
collection.insertMany(tmp1, {safe: true}).then(function (result) {
    // parse `result`
    console.log('----111111!');
}).then(function() {
    console.log('----22222222!');
}).catch(function(err) {
    console.log(`${err}`);
});

不好意思,代码没真实在node环境下运行过。如果你有空可以去试试,把结果或问题发出来,我这边更正下 :)。

【热门文章】
【热门文章】