async.await无法以同步方式工作?

时间:2018-10-18 18:27:35

标签: mongoose async-await

每个人,我都是NODE'S的初学者。我尝试了一个简单的程序在Mongoose中插入两个文档。我的代码运行正常。两个文档正确插入了db,但是在检索检索到的一个文档时,一旦两个文档保存在db中,我想调用resolve函数。但是这里保存了一个文档后,解析函数被调用回去。我想在 SYNC WAY(ONE BY ONE)中运行此代码。即,我使用了 async-await概念。尽管它以异步方式工作。我的结论是一次for循环结束了,然后只需要调用resolve函数。任何人都可以解决此问题。我在下面附加了代码以及我的输出和预期的输出。

var express = require('express');
var app = express();
var mongoose = require('mongoose');


mongoose.connect("mongodb://DWWW:RFEFE,@ds141902.mlab.com:41902/skyfall",{ useNewUrlParser: true },(err,db)=>{
         if(err)
         {
            return console.log(err.message);
         }
           console.log('db succesfully connected');
});

console.log('ok');

app.use('/', function (req, res) {

    if(req.url ==='/')
    {
        console.log('Request Url:' + req.url);
    
    var Schema = mongoose.Schema;

    var personSchema = new Schema({
        firstname: String,
        lastname: String,
        address: String
    });
    
    var Persondata = mongoose.model('doagain', personSchema);
    
    var data=[{
        firstname: 'John',
        lastname: 'Doe',
        address: '555 Main St.'
       },{
        firstname: 'Jane',
        lastname: 'Doe',
        address: '555 Main St.'
      }];
    var count=1;
    function savingprocess()
    {
        return new Promise((resolve,reject)=>{

               for(var i  in data)
               {
                   var details = Persondata(data[i]);
                   // save the user
                   details.save(function(err) {
                   if (err) reject('ERROR');
                   console.log(' person details saved!:'+count);
                   ++count;
                   });
               }
               resolve('SUCCESS');
               
        });
    }
    async function dosyncway()
    {
       let ans= await savingprocess();
       if(ans ==='SUCCESS')
       {
             // get all the users


	     Persondata.find({}, function(err, users) {

		 if (err) throw err;
		
        // object of all the users
        console.log("COMPLETE USER DATA:");
        console.log(users);
        res.end('Saved Successfully');
	    });
       }
       else{
           console.log('Problem');
       }
    }

    dosyncway();
    }
	
});

app.listen(8086,()=>{
    console.log('server is listening on port:8086');
});


MY OUTPUT:

ok
server is listening on port:8086
db succesfully connected
Request Url:/
 person details saved!:1
COMPLETE USER DATA:
[ { _id: 5bc8cafe54be522c449723d8,
    firstname: 'John',
    lastname: 'Doe',
    address: '555 Main St.',
    __v: 0 } ]
 person details saved!:2
 
 
 I'm expecting output:
 
 ok
server is listening on port:8086
db succesfully connected
Request Url:/
 person details saved!:1
 person details saved!:2
COMPLETE USER DATA:
[ { _id: 5bc8cafe54be522c449723d8,
    firstname: 'John',
    lastname: 'Doe',
    address: '555 Main St.',
    __v: 0 } ,
    { _id: 5bc8cafe54be522c449723d9,
    firstname: 'jane',
    lastname: 'kumar',
    address: 'chennai Main St.',
    __v: 0 }]
 person details saved!:2

任何人都可以更新此代码...提前感谢...

1 个答案:

答案 0 :(得分:0)

您的 save 调用将异步执行,这就是为什么在执行所有 save 回调之前您的诺言就会解决的原因。

我认为您正在寻找的是在回调中添加一项检查,以查看它是否是要完成的最后一项,然后才能兑现您的承诺:

// ...

for (var i in data) {
  var details = Persondata(data[i]);

  details.save(function(err) {
    if (err) reject('ERROR');

    console.log('person details saved!:' + count);

    // Check if this is the last data item before resolving promise
    if (count === data.length) {
      resolve('SUCCESS');
    }

    ++count;
  });
}

或者,如果要删除回调,则可以使用Promise.all()一起执行所有保存操作,然后等待结果。像这样:

// ...

function savingProcess() {
  const promises = data.map(item => Persondata(item).save());
  return Promise.all(promises);
}

async function doAsync() {
  try {
    const ans = await savingProcess();
    const users = await Persondata.find({});

    console.log('COMPLETE USER DATA:');
    console.log(users);
    res.end('Saved Successfully');
  }
  catch(err) {
    console.log('Problem');
    throw err;
  }
}

doAsync();