当我使用 Promise.map() 时,我要么得到一个 user_ids 数组,要么得到一个错误。当我使用 Promise.settle() 时,我获取的是数组的值,而不是数组中返回的 Promise 的值。我使用以下内容来更好地说明我的意思:
var Promise = require('bluebird');
var user_names = ['John','Mary'];
Promise.map(user_names, function(name){
//following will return a promise resolved with the db id
// or a rejection
return db.create(name);
}).then(function(user_ids){
//if db.create never failed I get an array of db ids
console.log(user_ids); //returns ['1','2']
}).catch(function(err){
//at least one of the db.create() failed
});
Promise.settle(user_names, function(name){
//following will return a promise resolved with the db id
// or a rejection
return db.create(name);
}).then(function(results){
//I get an array of PromiseInspection objects
if(results[0].isFulfilled()){
var value = results[0].value();
console.log(value); //returns 'John'
}
});
我的最终目标是取回一组 id。由于 Promise 可能被拒绝,该数组可能比 user_names
数组小。
最佳答案
Promise.settle
确实像 Promise.all
一样工作,而不是像 Promise.map
那样工作。它不接受一组值和回调,它接受一组promise(如果给定值,它会将它们解析为promise)。您的回调将被忽略。
您将自己调用该函数,使用 Array's .map
method :
Promise.settle(user_names.map(function(name) {
// ^^^^^
return db.create(name);
})).then(function(results) {
if (results[0].isFulfilled()) {
var value = results[0].value();
console.log(value); // returns the database id now
}
});
关于javascript - 如何获取 Bluebird Promise.settle() 的 promise 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236236/