等待2个允诺在一个函数中同时使用

首先:我希望我的问题还没有被问及其他地方的回答…我一直在寻找和networking上,我似乎无法find任何东西(也许这是不可能的)。

基本上,我试图build立一个数据库(在我的情况下与蒙戈)从webAPI(密码交换Kraken)获取信息。 目标是用我从请求中得到的各种对象构build我的集合。

这里的gitub回购: MongoNode

这里是当前的代码(我现在使用简单的callback和请求:链接一切):

// 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); }); 

我试图用承诺链接他们,但似乎无法find一个方法来工作。 这是我的诺言游乐场:

 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); }) ); 

以下是执行时在控制台中打印的内容:

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

预先感谢您的帮助,我希望这个问题还没有得到答复!

       

网上收集的解决方案 "等待2个允诺在一个函数中同时使用"

 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); }) );