我有这个承诺,Item如果在数据库中找不到它,则会创建一个新文档,然后将其存储在以前创建的Collection文档中.
Collection文档是数组中的第一个字符串,数组中的任何后续索引都转换为一个或多个Item文档.
Promise.each "解析为原始数组未修饰的"等等,最后return内的Promise.each被渲染的对象,但在随后.then产生原始阵列..
这是承诺(缩写为可读性):
globalVar = true;
collectionId = "";
var itemSeries = Promise.each(items, function(element) {
if (globalVar == true) {
return Models.Collection.findOneAsync({
"name": element
})
.then(function(collection) {
// promise chain similar to the following else..
// set the collectionId var to an _id
});
} else {
return Models.Items.findOneAsync({
"name": element
})
.then(function(item) {
if (item == null) {
return Models.Labels.findOneAsync({
"title": element
})
.then(function(label) {
var …Run Code Online (Sandbox Code Playgroud) 利用Bluebird来支持Mongoose,我有一个Promise.map(带有一系列if/else的函数用于循环遍历数组以查看是否存在引用doc,否则创建一个..
将findOneAsync的产品分配给变量,然后将'variable._id'分配给制作中的新doc(主要承诺),控制台日志 {"isFulfilled":false,"isRejected":false}
这是一个片段:
for (i=0; i<items.length; i++) {
var existingItem = Models.Items.findOneAsync({ item: items[i] });
console.log( "existingItem : ");
console.log( JSON.stringify(existingItem) );
console.log( "existingItem._id : " + existingItem._id );
Run Code Online (Sandbox Code Playgroud)
这是一个日志:
existingItem :
{"isFulfilled":false,"isRejected":false}
existingItem._id : undefined
Run Code Online (Sandbox Code Playgroud)
为什么existingItem变量可能等待Model.Item.findOneAsync ..?
这个问题已经以各种方式提出,但不是那么简单.
如何重写这个Promise.all以便promise1之前完全运行promise2?
var promise1 = function() { .. lots of promise stuff };
var promise2 = function() { .. lots more promise stuff };
Promise.all([promise1, promise2]).then(function() {
log.info("ran promise1 & promise2");
});
Run Code Online (Sandbox Code Playgroud)
Promise.all并行运行promise1和promise2.
利用express.Router()对我们的应用程序进行API调用:
var express = require('express');
var app = express();
var router = express.Router();
Run Code Online (Sandbox Code Playgroud)
router.use 每次API调用之前的console.logs:
router.use(function(req, res, next) { // run for any & all requests
console.log("Connection to the API.."); // set up logging for every API call
next(); // ..to the next routes from here..
});
Run Code Online (Sandbox Code Playgroud)
我们如何folder/routes.js从我们当前所在的主app.js导出我们的路线并从中访问它们:
router.route('/This') // on routes for /This
// post a new This (accessed by POST @ http://localhost:8888/api/v1/This)
.post(function(req, res) {
// do stuff
});
router.route('/That') // on routes for …Run Code Online (Sandbox Code Playgroud) javascript ×4
node.js ×4
bluebird ×3
promise ×3
asynchronous ×1
express ×1
mongoose ×1
routes ×1