代码之家  ›  专栏  ›  技术社区  ›  Martin Carre

等待2个承诺在函数中同时返回使用

  •  1
  • Martin Carre  · 技术社区  · 9 年前

    首先:我希望我的问题还没有在其他地方被问到和回答……我一直在网上搜索,似乎什么都找不到(也许根本不可能)。

    目标是用我从请求中获得的各种对象构建我的集合。

    这里是gitub回购: MongoNode

    // External Modules
    var request = require('request');
    var yargs = require('yargs');
    var _ = require('underscore');
    var async = require('async');
    var MongoClient = require('mongodb').MongoClient,
      co = require('co'),
      assert = require('assert');
    
    // Own Modules
    
    // Variables
    var tickerArr= []
    
    // Generator function for connection
    co(function*() {
      // Connection URL
      var url = 'mongodb://localhost:27017/CryptoDB';
      // Use connect method to connect to the Server
      var db = yield MongoClient.connect(url);
    
      // Inside the DB connection
      console.log('Connection up and running...');
    
      // Getting the list of the tickers for USD and EUR exclusively
      request({
        url:'https://api.kraken.com/0/public/AssetPairs',
        json: true
      }, (error, response, body) => {
        var jsonObject = body;
        _.map(jsonObject, function(content) {
          _.map(content, function(data) {
            if(data.altname.indexOf('EUR') !== -1 || data.altname.indexOf('USD') !== -1)
              tickerArr.push(data.altname);
          });
        });
        // Getting the ticker info for each USD && EUR ticker available
        async.forEach(tickerArr, (item) => {
          request({
            url:`https://api.kraken.com/0/public/Ticker?pair=${item}`,
            json: true
          }, (error, response, body) => {
                  db.collection('Assets').insertOne(
                    body.result,
                    request({
                          url:'https://api.kraken.com/0/public/Time',
                          json: true
                        }, (error, response, body) => {
                            return body.result;
                        })
                      );
                  console.log('Asset Added!', body.result);
          });
        });
      });
      // Closing the DB connection
      // db.close();
      }).catch(function(err) {
      console.log(err.stack);
    });
    

    这是我的承诺:

    var somePromise1 = new Promise((resolve, reject) => {
      resolve('Hey! It worked!');
    });
    
    var somePromise2 = new Promise((resolve, reject) => {
      resolve('Hey! It worked the second time!');
    });
    
    somePromise1.then(somePromise2.then((message1, message2) => {
      console.log('Success', message1, message2);
    })
    );
    

    $Success嘿!第二次成功了!未定义

    提前谢谢你的帮助,我希望这个问题还没有被回答过一百万次!

    1 回复  |  直到 9 年前
        1
  •  3
  •   marzelin    9 年前

    var somePromise1 = new Promise((resolve, reject) => {
      resolve('Hey! It worked!');
    });
    
    var somePromise2 = new Promise((resolve, reject) => {
      resolve('Hey! It worked the second time!');
    });
    
    somePromise1.then((message1) => somePromise2.then((message2) => {
      console.log('Success', message1, message2);
    })
    );

    然而,承诺是相当复杂的。 async/await

    var somePromise1 = new Promise((resolve, reject) => {
      resolve('Hey! It worked!');
    });
    
    var somePromise2 = new Promise((resolve, reject) => {
      resolve('Hey! It worked the second time!');
    });
    
    
    async function exec() {
      const message1 = await somePromise1
      const message2 = await somePromise2
      console.log('Success', message1, message2);
    }
    
    exec()
    推荐文章